0

我在这里有一个工资单程序,我希望能够将对象添加到 Employee 类。目前我定义了与 Employee 类相关的对象 emp。如果我希望能够动态创建对象,直到我在脚本中输入 STOP 命令。此外,一旦我完成了如何打印与 Employee 类相关的所有对象。提前致谢。

import java.util.Scanner;

class PayrollProgram
{


public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);

    List<Employee> employees = new ArrayList<>();

    while (!emp.name.equals("STOP"))
    {
    Employee emp = new Employee();

    System.out.print("Employee's Name: ");
    emp.name = scan.next();

    if(emp.name.equals("STOP"))
        {
            System.out.printf("The Application is STOPPING......");
        break;
        }

    System.out.print("Enter hourly wage: $ ");
    emp.wage = scan.nextDouble();
    while (emp.wage < 0) 
    {
        System.out.printf("Please Enter a Positive Number! \n");
        System.out.print("Enter hourly wage: $ ");  
        emp.wage = scan.nextDouble();
    }

    System.out.print("Hours Worked in Week: ");
    emp.hours = scan.nextDouble();
    while (emp.hours < 0) 
    {
        System.out.printf("Please Enter a Positive Number! \n");
        System.out.print("Hours Worked in Week: ");
        emp.hours = scan.nextDouble();
    }

    employees.add(emp);
    emp.printEmployee();

    }
    for(Employee emp : employees)
        {
        System.outprintln(emp.name);
        }
}

}
4

1 回答 1

1

保留一个包含每个员工的数据结构(在这种情况下通常是一个列表)。每个循环您只需创建一个新员工并将其添加到列表中。之后,您可以打印所有内容。

List<Employee> employees = new ArrayList<>();

while (!emp.name.equals("STOP")) {
 Employee emp = new Employee();
 // read all the data from input

 employees.add(emp);
}

for(Employee emp : employees) {
 System.out.println(emp.name);
}
于 2013-10-16T01:25:49.760 回答