我这里有一个工资单程序,我希望能够将对象添加到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);
}
}
}
答案 0 :(得分: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);
}