当我尝试将字符串添加到数组列表时,我得到一个"非法的类型错误启动"

时间:2018-03-19 18:34:21

标签: java arrays arraylist

我有一个数组列表,用于保存员工ID号,但是当我尝试添加String时,它给出了我的名义错误。我读到我可以通过将我的添加内容移动到构造函数或方法中来解决这个问题,但是出于这个数组列表的目的,我不能这样做,因为我也将从中删除对象。我非法开始是什么类型的?我使用Blue J.这不是完整的程序,只有构造函数和它上面的内容。

import java.util.Scanner;
import java.util.ArrayList;
public class Employee{
  static Scanner scan = new Scanner (System.in);

  private static ArrayList<String> employeeID = new ArrayList<String>();
  employeeID.add<"632584">;
  employeeID.add<"259415">;
  employeeID.add<"257412">;
  employeeID.add<"953647">;
  employeeID.add<"126497">;
  employeeID.add<"453256">;
  employeeID.add<"125689">;

  private String employeeName; //A String to hold an employee’s full name.

  private int hours; //An integer to hold the number of hours worked by each employee.
  private double payRate; //A double to hold each employee’s hourly pay rate.
  private double wages; //A doubles to hold each employee’s gross wages. 
  private String ID; // A string to hold each employee's ID.

  /**
   * Create a new employee on the payroll with a given name, hours, pay rate, and wages.
   */
  public Employee(){

    ID = employeeID[0];

    System.out.println("What is the employee's full name?");
    employeeName = scan.nextLine();
    System.out.println("");

    System.out.println("What is the employee's hourly pay rate?");
    payRate = scan.nextInt();
    scan.nextLine(); //consumes next line
    System.out.println("");
  }
}

1 个答案:

答案 0 :(得分:0)

要将项目添加到静态列表,您可以使用块static {}

public class Employee {
....

 private static ArrayList <String> employeeID = new ArrayList <String> ();
 static {
  employeeID.add("632584");
  employeeID.add("259415");
  employeeID.add("257412");
  employeeID.add("953647");
  employeeID.add("126497");
  employeeID.add("453256");
  employeeID.add("125689");
 }

...
 }
}

或使用构造函数

public class Employee {
....

 private static ArrayList <String> employeeID = new ArrayList <String> ()
 {{
  add("632584");
  add("259415");
  add("257412");
  add("953647");
  add("126497");
  add("453256");
  add("125689");
 }};

...
 }
}