当有多个类时,ArrayLists 的 Java 问题并帮助修复代码 [英] Java trouble with ArrayLists when there are multiple classes and help fixing up the code

查看:41
本文介绍了当有多个类时,ArrayLists 的 Java 问题并帮助修复代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得出的结论是我有 3 个问题.

  1. 如何在Employee类中使用company类的变量和arrayList.
  2. 我应该如何制作 actionListeners 以便正确运行.
  3. Company 类中的方法是否能正常工作?如果没有,我应该如何制作它们?

检查上面段落中给出的链接,以获取我的问题的提示.这是我的教授提供的提示的链接 https://www.dropbox.com/s/omeg19u6ns2pot2/Work%205.doc 所以你们可以看到我想要达到的目标.我通常会从导师那里得到帮助,但他们现在特别不可用.帮助真的非常非常感谢.我必须在今晚之前完成这件事.我知道这对本网站来说有点过分,但这是您可以很好地了解正在发生的事情的唯一方法.我已经开始写一篇关于这个问题的帖子并进一步移动,但没有人再回复我关于那个帖子的问题,所以我正在做另一个.

这是图形用户界面,也就是驱动程序

import java.awt.*;导入 javax.swing.*;导入 java.awt.event.*;导入 java.util.ArrayList;公共类 GUI 扩展 JFrame {私人 JPanel 员工面板;私人 JPanel buttonPanel2;私人 JPanel 位置面板;私有 JPanel 名称Panel2;私人 JPanel buttonPanel1;私人 JPanel 上线;私人 JPanel 下线;私人JPanel公司和PresidentPanel;私人JPanel公司面板;私人 JRadioButton 设计按钮;私人 JRadioButton salesButton;私人 JRadioButton manuButton;私人 JTextField firstField;私有 JTextField lastField;私人 JLabel firstLabel;私有 JLabel lastLabel;私人 JLabel cNameLabel;私人 JLabel 总裁标签;私人 JLabel 标志;私有 ButtonGroup bGroup;private static final long serialVersionUID = 1L;c公司;员工e;私有 JButton 添加按钮;私有 JButton 清除按钮;私人 JButton 打印按钮;私有 JButton 新按钮;私有 JButton 退出按钮;字符串公司名称;公共图形用户界面(){公司名称 = JOptionPane.showInputDialog("这家公司叫什么名字", companyName);setTitle("公司员工");设置大小(425、450);setLayout(new BorderLayout());setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);主要的();子面板();添加(companyAndPresidentPanel,BorderLayout.NORTH);添加(员工面板,BorderLayout.CENTER);添加(buttonPanel1,BorderLayout.SOUTH);设置可见(真);//盒();}公共无效子面板(){positionPanel = new JPanel();buttonPanel1 = new JPanel();buttonPanel2 = new JPanel();员工面板 = 新的 JPanel();namePanel2 = new JPanel();upperLine = new JPanel();下线 = 新的 JPanel();employeePanel.setSize(new Dimension(100, 100));designButton = new JRadioButton("设计");salesButton = new JRadioButton("销售");manuButton = new JRadioButton("制造");addButton = new JButton("添加员工");clearButton = new JButton("清除按钮");printButton = new JButton("打印公司员工");newButton = new JButton("新公司");exitButton = new JButton("退出");firstField = new JTextField(10);lastField = new JTextField(10);firstLabel = new JLabel("名字:");lastLabel = new JLabel("姓氏:");bGroup = new ButtonGroup();bGroup.add(designButton);bGroup.add(salesButton);bGroup.add(manuButton);positionPanel.setLayout(new FlowLayout());positionPanel.add(designButton);positionPanel.add(salesButton);positionPanel.add(manuButton);positionPanel.setBorder(BorderFactory.createTitledBorder("Position"));upperLine.add(printButton);lowerLine.add(newButton);lowerLine.add(exitButton);buttonPanel1.add(upperLine, BorderLayout.NORTH);buttonPanel1.add(lowerLine, BorderLayout.SOUTH);buttonPanel2.add(addButton);buttonPanel2.add(clearButton);namePanel2.setLayout(new GridLayout(2, 2));namePanel2.add(firstLabel);namePanel2.add(firstField);namePanel2.add(lastLabel);namePanel2.add(lastField);employeePanel.setBorder(BorderFactory.createTitledBorder("添加员工"));employeePanel.add(namePanel2, BorderLayout.NORTH);employeePanel.add(positionPanel, BorderLayout.CENTER);employeePanel.add(buttonPanel2, BorderLayout.SOUTH);employeePanel.setBorder(BorderFactory.createTitledBorder("添加员工"));printButton.addActionListener(new aListener());addButton.addActionListener(new aListener());clearButton.addActionListener(new aListener());newButton.addActionListener(new aListener());exitButton.addActionListener(new aListener());}/** 如果数据 manager.add employee.equals("too many design") joption pane too* 许多*/公共无效主(){companyAndPresidentPanel = new JPanel();公司面板 = 新的 JPanel();PresidentLabel = new JLabel("总统:阿明·奥斯库伊");cNameLabel = new JLabel("");logo = new JLabel("");cNameLabel.setText(companyName);ImageIcon myImage = new ImageIcon("src/company.png");logo.setIcon(myImage);companyPanel.add(logo);companyPanel.add(cNameLabel);companyAndPresidentPanel.setLayout(new GridLayout(2, 1));companyAndPresidentPanel.add(companyPanel);companyAndPresidentPanel.add(presidentLabel);}私有类 aListener 实现 ActionListener {字符串 fName;字符串 lName,位置;int nEmployees、nCompanies、nDesign、nSales、nManu;public void actionPerformed(ActionEvent e) {//TODO 自动生成的方法存根if (e.getSource() == addButton) {fName = firstField.getText();lName = lastField.getText();if (e.getSource() instanceof JRadioButton) {如果(manuButton.isSelected()){位置 = (manuButton.getText());} else if (designButton.isSelected()) {位置 = (designButton.getText());} else if (salesButton.isSelected()) {位置 = (salesButton.getText());}c = 新公司(nEmployees、nCompanies、nDesign、nSales、nManu);c.addEmployee(fName, lName, position);c.printCompany();}} else if (e.getSource() == clearButton) {firstField.setText("");lastField.setText("");bGroup.clearSelection();} else if (e.getSource() == printButton) {} else if (e.getSource() == newButton) {} else if (e.getSource() == exitButton) {System.exit(0);}}}公共静态无效主(字符串 [] args){新的图形用户界面();}}

这里是数据管理员

import javax.swing.*;导入 java.util.*;公共类公司{private static final long serialVersionUID = 1L;//保证类对应一个序列化的对象员工一;private String companyName;//公司名称私人字符串员工姓名;私人字符串位置;最终 int maxCompanies = 2, maxEmployees = 7, maxSales = 1, maxDesign = 2, maxManufacturing = 4;private static int numberOfCompanies;//公司数量private int numEmployees;//员工人数public int numDesign;//设计人员人数private int numManufacturing;//制造业员工人数private int numSales;//销售员工人数私有 ArrayList<员工>员工名单;公众公司(字符串cn){员工人数 = 0;销售数量 = 0;数字设计 = 0;numManufacturing = 0;员工列表 = 新数组列表<员工>();}公共公司(int ec,int nc,int nd,int ns,int nm){员工人数 = ec;numberOfCompanies = nc;numDesign = nd;numSales = ns;numManufacturing = nm;}public String addEmployee(String fName, String lName, Position p) {字符串错误消息;errorMessage = "这是错误之一";开关 (p) {案例销售://如果销售员少于1个,将他们添加到列表中如果 (numSales < maxSales && numEmployees< maxEmployees) {雇员雇员=新雇员(fName,lName,p);员工列表.添加(员工);numSales++;员工人数++;}别的 {JOptionPane.showMessageDialog(null, "已经有销售代表.");}案例设计:如果 (numDesign < maxEmployees && numEmployees< maxEmployees) {雇员雇员=新雇员(fName,lName,p);员工列表.添加(员工);numDesign++;员工人数++;}别的 {JOptionPane.showMessageDialog(null, "已经有两个设计人员了.");}案例制造:if (numManufacturing < maxManufacturing && numEmployees< maxEmployees){雇员雇员=新雇员(fName,lName,p);员工列表.添加(员工);numManufacturing++;员工人数++;}别的 {JOptionPane.showMessageDialog(null, "已经有四家厂商了.");}默认:}返回错误信息;}public static int getNumCompanys(){//返回公司数量返回 numberOfCompanies;}public int getNumEmployees(){//获取员工人数返回 numEmployees;}public String printCompany(){//打印公司的所有职位String companyPrint = companyName + "\n";返回公司名称;}@覆盖public String toString() {//将所有内容转换为字符串返回公司[位置="+,公司名称="+公司名称+",雇员="+employeeList+",numEmployees="+numEmployees+ ", numDesign=" + numDesign + ", numManufacturing="+ numManufacturing + ", numSales=" + numSales + "]";}}

这是编辑后的 ​​Employee 类.

 import javax.swing.JOptionPane;公共类员工{公共员工(字符串 fName,字符串 lName,职位 p2){员工员工=新员工(fName,lName,p2);public boolean addEmployee(String fName2, String lName2, Position p3) {开关 (p) {案例销售://如果销售员少于1个,将他们添加到列表中如果 (numSales <1) {雇员雇员2 = 新雇员(fName2, lName2, p3);员工列表.添加(员工);}别的 {JOptionPane.showMessageDialog(null, "已经有销售代表.");}休息;案例设计:如果 (numDesign <2) {雇员雇员2 = 新雇员(fName2, lName2, p3);员工列表.添加(员工 2);}别的 {JOptionPane.showMessageDialog(null, "已经有两个设计人员了.");}休息;案例制造:如果 (numManu <4){雇员雇员2 = 新雇员(fName2, lName2, p3);员工列表.添加(员工 2);}别的 {JOptionPane.showMessageDialog(null, "已经有四家厂商了.");}默认:休息;}}}字符串名字;字符串姓氏;位置 p;}

这是枚举类,也是我寻求帮助的原因之一.

//在Position.java中公共枚举位置{设计(设计"),制造(制造"),销售(销售");私人最终字符串位置名称;私人位置(字符串位置名称){this.positionName= positionName;}@覆盖公共字符串 toString() {返回位置名称;}}

解决方案

枚举被用作一种伪类型.您确实需要枚举类,因为 1. 它是您作业的一部分,2. 它使阅读您的代码的任何人(包括您自己)更清楚某些值的含义.

如果你有一些枚举 Day 和一些变量 day1,当你编写 if (day1.toString.equals("MONDAY")) 时很容易看出你在做什么,但是如果你使用幻数/预定义常量,它看起来像 if (day1 == 0) 这对于没有编写代码的任何人(以及将来可能是你,当你'再看看这段代码)

除此之外,使用 enum 不允许垃圾值.如果您不使用枚举,则可以将 day1 定义为 10,000,这将是有效的 Java.如果您一周只有 7 天,这是一个荒谬的值.枚举提供了一个抽象层,可以避免垃圾值,并让您明确控制枚举的处理方式.

位置枚举的实现

//在Position.java中公共枚举位置{设计(设计"),制造(制造"),销售(销售");私人最终字符串位置名称;//注意枚举有私有构造函数私人位置(字符串位置名称){this.positionName= positionName;}//您正在覆盖默认的 toString() 方法//为Java中的所有对象定义,所以添加@Override@覆盖公共字符串 toString() {返回位置名称;}}

因此在你的 Employee 类中你声明了一个 Employee :

Employee employee = new Employee("John", "Deer", DESIGN);

由于您要跟踪您拥有的每个职位的数量,您需要在 Company 中创建一个属性,用于存储给定类型的员工数量.>

因此,在Company 的属性声明中,您将创建 3 个整数:

private int numOfDesigners;私人 int numOfManufacturers;私人 int numOfSalesmen;

无论何时添加员工,您都希望确保已经没有太多员工,因此您会将 Employee 类的创建封装在一个 public boolean addEmployee(StringfName, String lName, Position p) 方法,如果位置 p 已经太多,则返回 false.

public boolean addEmployee(String fName, String lName, Position p) {//因为这个方法会在Company类中,所以我们可以直接//引用特定仓位类型的编号//我假设你知道switch语句是如何工作的.开关 (p) {案例销售://如果销售员少于1个,将他们添加到列表中如果 (numOfSalesmen <1) {雇员雇员=新雇员(fName,lName,p);//假设你命名你的 ArrayList'员工名单'StaffList.add(员工);}别的 {//使用GUI提供一些错误消息或一些功能}休息;案例设计:如果 (numOfDesigners <2) {...}休息;...默认://一些错误处理休息;}}


其次,您需要在 Company 类中声明一些 ArrayList 作为属性.在 Company 类中编写一个函数,以某种方式检查特定类型的员工是否过多,并相应地返回一个值.

在面向对象编程中,您提供处理类属性的函数,以便其他类不必担心函数是如何实现的(这称为封装).

也就是说,如果您想打印 GUI 类中的所有员工姓名,您可以定义一个对象 Company,将员工添加到它的 ArrayList 属性并打印出 a 的返回值返回Bob M., Stacy J., John A"的函数 public String listOfEmployees()或者您想以何种方式实施它.

这样,当您需要员工列表时,您就不必遍历 Company 类中的 Employees 列表并以任意方式将它们连接起来到单个字符串.函数 listOfEmployees() 为你做这件事,假设你有一个名为 company1Company 你可以简单地写:

String currentList = company.listOfEmployees();

而不是把你的代码弄得乱七八糟

String currentList = "";for (员工 e : 员工列表) {currentList += e.firstName + e.lastName;}

此外,OOP 最有价值的方面之一是它允许您更改功能而无需记住您在哪里使用了此代码.如果出于某种原因您的应用程序现在应该只打印出名字怎么办?您必须找到此 for 循环的每个实例,并从中间的语句中删除 + e.lastName.如果您正确封装了 listOfEmployees() 函数,您只需在此函数中进行更改,而不必担心更改每次用法.

这是让您的班级以清晰且可预测的方式相互互动的方式.

I've come to the conclusion that I have 3 questions.

  1. How do I use the variables and arrayList of the company class in the Employee class.
  2. How should I make the actionListeners so the operate correctly.
  3. Would the methods in the Company class work correctly? If not, how should I make them?

Check the link given in the paragraph above for the prompt to my question. Here is a link to the prompt my professor has provided https://www.dropbox.com/s/omeg19u6ns2pot2/Work%205.doc so you guys can see what I am trying to reach. I would usually get help from the tutors but they aren't available at this time in particular. Help is really, really highly appreciated. I have to finish this by tonight. I know this is a bit too much for this website but it is the only way you can get a good grasp on what is happening. I have already started a post on this problem and moved a bit further but no one is replyting to my questions on that post anymore so I am doing another one.

Here is the GUI aka the driver

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;

public class GUI extends JFrame {

   private JPanel employeePanel;
   private JPanel buttonPanel2;
   private JPanel positionPanel;
   private JPanel namePanel2;
   private JPanel buttonPanel1;
   private JPanel upperLine;
   private JPanel lowerLine;
   private JPanel companyAndPresidentPanel;
   private JPanel companyPanel;
   private JRadioButton designButton;
   private JRadioButton salesButton;
   private JRadioButton manuButton;
   private JTextField firstField;
   private JTextField lastField;
   private JLabel firstLabel;
   private JLabel lastLabel;
   private JLabel cNameLabel;
   private JLabel presidentLabel;
   private JLabel logo;
   private ButtonGroup bGroup;
   private static final long serialVersionUID = 1L;

   Company c;
   Employee e;
   private JButton addButton;
   private JButton clearButton;
   private JButton printButton;
   private JButton newButton;
   private JButton exitButton;

   String companyName;

   public GUI() {

      companyName = JOptionPane.showInputDialog(
            "What is the name of this company", companyName);
      setTitle("Company Employees");
      setSize(425, 450);
      setLayout(new BorderLayout());
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      main();
      subPanels();
      add(companyAndPresidentPanel, BorderLayout.NORTH);
      add(employeePanel, BorderLayout.CENTER);
      add(buttonPanel1, BorderLayout.SOUTH);

      setVisible(true);

      // pack();

   }

   public void subPanels() {

      positionPanel = new JPanel();
      buttonPanel1 = new JPanel();
      buttonPanel2 = new JPanel();
      employeePanel = new JPanel();
      namePanel2 = new JPanel();
      upperLine = new JPanel();
      lowerLine = new JPanel();
      employeePanel.setSize(new Dimension(100, 100));
      designButton = new JRadioButton("Design");
      salesButton = new JRadioButton("Sales");
      manuButton = new JRadioButton("Manufacturing");

      addButton = new JButton("Add Employee");
      clearButton = new JButton("Clear Button");
      printButton = new JButton("Print Company Employees");
      newButton = new JButton("New Company");
      exitButton = new JButton("Exit");

      firstField = new JTextField(10);
      lastField = new JTextField(10);

      firstLabel = new JLabel("First Name:");
      lastLabel = new JLabel("Last Name:");

      bGroup = new ButtonGroup();
      bGroup.add(designButton);
      bGroup.add(salesButton);
      bGroup.add(manuButton);

      positionPanel.setLayout(new FlowLayout());
      positionPanel.add(designButton);
      positionPanel.add(salesButton);
      positionPanel.add(manuButton);
      positionPanel.setBorder(BorderFactory.createTitledBorder("Position"));

      upperLine.add(printButton);
      lowerLine.add(newButton);
      lowerLine.add(exitButton);
      buttonPanel1.add(upperLine, BorderLayout.NORTH);
      buttonPanel1.add(lowerLine, BorderLayout.SOUTH);

      buttonPanel2.add(addButton);
      buttonPanel2.add(clearButton);

      namePanel2.setLayout(new GridLayout(2, 2));
      namePanel2.add(firstLabel);
      namePanel2.add(firstField);
      namePanel2.add(lastLabel);
      namePanel2.add(lastField);

      employeePanel.setBorder(BorderFactory.createTitledBorder("Add Employee"));
      employeePanel.add(namePanel2, BorderLayout.NORTH);
      employeePanel.add(positionPanel, BorderLayout.CENTER);
      employeePanel.add(buttonPanel2, BorderLayout.SOUTH);
      employeePanel.setBorder(BorderFactory.createTitledBorder("Add Employee"));

      printButton.addActionListener(new aListener());
      addButton.addActionListener(new aListener());
      clearButton.addActionListener(new aListener());
      newButton.addActionListener(new aListener());
      exitButton.addActionListener(new aListener());

   }

   /*
    * if data manager.add employee.equals("too many design") joption pane too
    * many
    */
   public void main() {

      companyAndPresidentPanel = new JPanel();
      companyPanel = new JPanel();
      presidentLabel = new JLabel("President:Amin Oskoui");
      cNameLabel = new JLabel("");
      logo = new JLabel("");
      cNameLabel.setText(companyName);

      ImageIcon myImage = new ImageIcon("src/company.png");
      logo.setIcon(myImage);

      companyPanel.add(logo);
      companyPanel.add(cNameLabel);

      companyAndPresidentPanel.setLayout(new GridLayout(2, 1));
      companyAndPresidentPanel.add(companyPanel);
      companyAndPresidentPanel.add(presidentLabel);

   }

   private class aListener implements ActionListener {
      String fName;
      String lName, position;
      int nEmployees, nCompanies, nDesign, nSales, nManu;

      public void actionPerformed(ActionEvent e) {
         // TODO Auto-generated method stub

         if (e.getSource() == addButton) {
            fName = firstField.getText();
            lName = lastField.getText();
            if (e.getSource() instanceof JRadioButton) {
               if (manuButton.isSelected()) {
                  position = (manuButton.getText());
               } else if (designButton.isSelected()) {
                  position = (designButton.getText());
               } else if (salesButton.isSelected()) {
                  position = (salesButton.getText());
               }
               c = new Company(nEmployees, nCompanies, nDesign, nSales, nManu);
               c.addEmployee(fName, lName, position);
               c.printCompany();

            }
         } else if (e.getSource() == clearButton) {
            firstField.setText("");
            lastField.setText("");
            bGroup.clearSelection();

         } else if (e.getSource() == printButton) {

         } else if (e.getSource() == newButton) {

         } else if (e.getSource() == exitButton) {
            System.exit(0);

         }

      }

   }

   public static void main(String[] args) {
      new GUI();
   }
}

Here is the Data Manager

import javax.swing.*;

import java.util.*;
public class Company {
private static final long serialVersionUID = 1L;//ensuring that the class corresponds with a serialized object


Employee a;

private String companyName;//name of company
private String employeeName;
private String position;

final int maxCompanies = 2, maxEmployees = 7, maxSales = 1, maxDesign = 2, maxManufacturing = 4;

private static int numberOfCompanies;//the number of companies
private int numEmployees;//the number of employees
public int numDesign;//the number of employees in design
private int numManufacturing;// the number of employees in manufacturing
private int numSales;//the number of employees in sales

private ArrayList<Employee> employeeList;


public Company(String cn){
    numEmployees = 0;
    numSales = 0;
    numDesign = 0;
    numManufacturing = 0;
    employeeList = new ArrayList<Employee>();
}
public Company(int ec, int nc, int nd, int ns,int nm) {
    numEmployees = ec;
    numberOfCompanies = nc;
    numDesign = nd;
    numSales = ns;
    numManufacturing = nm;
}
public String addEmployee(String fName, String lName, Position p) {
       String errorMessage;
       errorMessage = "It is one of the errors";

    switch (p) {
        case SALES:
            //if there's less than 1 salesman, add them to the list

            if (numSales < maxSales && numEmployees< maxEmployees) {
                Employee employee = new Employee(fName, lName, p);
                employeeList.add(employee);
                numSales++;
                numEmployees++;
            }
            else {
                JOptionPane.showMessageDialog(null, "There is already a Sales representative.");

                }


        case DESIGN:
            if (numDesign < maxEmployees && numEmployees< maxEmployees) {
                Employee employee = new Employee(fName, lName, p);
                employeeList.add(employee);
                numDesign++;
                numEmployees++;
            }
            else {
                JOptionPane.showMessageDialog(null, "There are already two design employees.");            
                }


        case MANUFACTURING:
            if (numManufacturing < maxManufacturing && numEmployees< maxEmployees){
                Employee employee = new Employee(fName, lName, p);
                employeeList.add(employee);
                numManufacturing++;
                numEmployees++;
            }
            else {
                JOptionPane.showMessageDialog(null, "There are already four manufacturers.");              
                }
        default:


    }
    return errorMessage;
    }
public static int getNumCompanies(){//return the number of companies 
    return numberOfCompanies;
}
public int getNumEmployees(){//get the number of employees
    return numEmployees;
}
public String printCompany(){//print the company with all of the positions
    String companyPrint = companyName + "\n";

    return companyName;
}
@Override
public String toString() {//converts everything to a string
    return "Company [position="  + ", companyName=" + companyName
            + ", employees=" + employeeList + ", numEmployees=" + numEmployees
            + ", numDesign=" + numDesign + ", numManufacturing="
            + numManufacturing + ", numSales=" + numSales + "]";
}

}

Here is the edited Employee class.

  import javax.swing.JOptionPane;

  public class Employee {

  public Employee(String fName, String lName, Position p2) {
Employee employee = new Employee (fName, lName, p2);
public boolean addEmployee(String fName2, String lName2, Position p3) {

    switch (p) {
        case SALES:
            //if there's less than 1 salesman, add them to the list
            if (numSales < 1) {
                Employee employee2 = new Employee(fName2, lName2, p3);
                employeeList.add(employee);
            }
            else {
                JOptionPane.showMessageDialog(null, "There is already a Sales representative.");               
                }
            break;

        case DESIGN:
            if (numDesign < 2) {
                Employee employee2 = new Employee(fName2, lName2, p3);
                employeeList.add(employee2);
            }
            else {
                JOptionPane.showMessageDialog(null, "There are already two design employees.");            
                }
            break;

        case MANUFACTURING:
            if (numManu < 4){
                Employee employee2 = new Employee(fName2, lName2, p3);
                employeeList.add(employee2);
            }
            else {
                JOptionPane.showMessageDialog(null, "There are already four manufacturers.");              
                }
        default:

            break;
    }
}
}
   String firstName;
   String lastName;
   Position p;


 }

Here is the enum class and one of the reasons i'm asking for help.

 //in Position.java
public enum Position {
DESIGN("Design"),
MANUFACTURING("Manufacturing"),
SALES("Sales");

private final String positionName;


private Position(String positionName) {
    this.positionName= positionName;
}


@Override
public String toString() {
    return positionName;
}
}

解决方案

An enum is used as a sort of pseudo-type. You do need the enumerated class because 1. it's part of your assignment and 2. it makes it just clearer to anyone reading your code (including yourself) what certain values mean.

If you have some enum Day and some variable day1, it's easy to see what you're doing when you write if (day1.toString.equals("MONDAY")) but if you use magic numbers/pre-defined constants, it will look like if (day1 == 0) which is meaningless to anyone who didn't write the code (and possibly you in the future, when you're looking at this code again).

In addition to that, using an enum disallows for garbage values. If you weren't using enums, you could define day1 to be 10,000 and it would be valid Java. This is a nonsensical value if you only have 7 days of the week. Enums provide a layer of abstraction that avoid garbage values and gives you explicit control over how an Enum is handled.

Implementation of the Position enum

//in Position.java
public enum Position {
    DESIGN("Design"),
    MANUFACTURING("Manufacturing"),
    SALES("Sales");
    
    private final String positionName;
    
    //note enums have private constructors
    private Position(String positionName) {
        this.positionName= positionName;
    }

    //you're overriding the default toString() method
    //defined for all objects in Java, so add @Override
    @Override
    public String toString() {
        return positionName;
    }
}

Thus in your Employee class you declare an Employee with:

Employee employee = new Employee("John", "Deer", DESIGN);

Since you're going to want to keep track of how many of each position you have, you need to create an attribute in Company that stores the number of employees of a given type.

So in Company in your attribute declaration you will create 3 integers:

private int numOfDesigners;
private int numOfManufacturers;
private int numOfSalesmen;

Whenever you add an employee, you want to make sure there aren't too many already, so you'll encapsulate the creation of the Employee class inside an public boolean addEmployee(String fName, String lName, Position p) method that returns false if there are too many of the Position p already.

public boolean addEmployee(String fName, String lName, Position p) {
    //since this method will be in the Company class, we can directly
    //refer to the number of a specific position type
    //I'm going to assume you know how a switch statement works.
    switch (p) {
        case SALES:
            //if there's less than 1 salesman, add them to the list
            if (numOfSalesmen < 1) {
                Employee employee = new Employee(fName, lName, p);
                //assuming you name your ArrayList<Employee> 'staffList'
                staffList.add(employee);
            }
            else {
                //give some error message or some functionality with GUI
            }
            break;

        case DESIGN:
            if (numOfDesigners < 2) {
                ...
            }
            break;
            
        ...

        default:
            //some error handling
            break;
    }
}


Secondly, you need to declare some ArrayList<Employee> in your Company class as an attribute. Write a function in the Company class that somehow checks whether or not there are too many employees of a particular type and returns a value accordingly.

In Object-Oriented Programming you provide functions for handling attributes of a class so that other classes don't have to worry about how a function is implemented (this is called encapsulation).

That is, if you want to print all the Employee names from your GUI class, you define an object Company, add Employees to it's ArrayList<Employee> attribute and print out the returned value of a function public String listOfEmployees() that returns "Bob M., Stacy J., John A" or however you want to implement it.

That way when you need the list of employees, you don't have to iterate over the list of Employees in the Company class and concatenate them in some arbitrary way to a single string. The function listOfEmployees() does that for you and assuming you have a Company called company1 you can simply write:

String currentList = company.listOfEmployees();

rather than cluttering your code up with

String currentList = "";
for (Employee e : employeeList) {
    currentList += e.firstName + e.lastName;
}

Also, one of the most valuable aspects of OOP is that it allows you to change functionality without having to remember where you used this code. What if for some reason your application should only print out the first names now? You have to find every instance of this for loop and remove the + e.lastName from the statement in the middle. If you have properly encapsulated the listOfEmployees() function, you simply make the change in this function and never have to worry about changing every usage.

This is how you can get your classes to interact with each other in a clear and predictable way.

这篇关于当有多个类时,ArrayLists 的 Java 问题并帮助修复代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆