3

我正在尝试使用 afor loop来允许用户设置我的类的对象。

老实说,这是一个homework project,但我们还没有做到for loops,我只是觉得稍微先进一点会很酷。

但是,当我键入将输入发送到方法的部分时,它表示该non-static变量不能在static上下文中使用。

有没有办法做到这一点,还是我必须使用 2X 的变量和代码行来设置这些对象?

这是带有 for 循环的部分

 for (int x=1; x<=2; x++)
   {
    //get input before setting up 2 objects of Employee
    Scanner input = new Scanner ( System.in);
    System.out.print("\nPlease enter the employee's name");
    name = input.nextLine();

    Scanner input1 = new Scanner ( System.in);
    System.out.print("\nPlease enter the employee's department");
    dept = input1.nextLine();

    Scanner input2 = new Scanner ( System.in);
    System.out.print("\nPlease enter the employee's name");
    wage = input2.nextdouble();

    // set Employee objects 
    if (x == 1) {
        Employee_irishRodger employee1 = new Employee_irishRodger(name, dept, wage);
    } else {
        Employee_irishRodger employee2 = new Employee_irishRodger(name, dept, wage);
    }

}
4

3 回答 3

3

I'm assuming name, dept and wage are the non-static fields of some class. The reason you are receiving an error is because the method in which you are using the for-loop is in fact static (not associated with each instance of your class) and hence your non-static fields can not be accessed through it. Try removing the static keyword from your method header.

You can read more about the static keyword here.


On another note, you don't need to create a new Scanner each time, you can just keep using input. Furthermore, you can instantiate this Scanner outside the scope of the for loop:

Scanner input = new Scanner(System.in);
for (int x = 1 ; x <= 2 ; x++) {
    System.out.print("\nPlease enter the employee's name");
    name = input.nextLine();

    System.out.print("\nPlease enter the employee's department");
    dept = input.nextLine();

    System.out.print("\nPlease enter the employee's name");
    wage = input.nextdouble();

    ...
}
input.close();  // don't forget to close the scanner when you're done

We've gone from 6 Scanner instantiations to 1.

于 2012-10-07T17:50:56.413 回答
3

我会更像这样。您可以拥有任意数量的员工:

Scanner input = new Scanner(System.in);
int numEmployees = 5;
List<Employee_irishRodger> employees = new List<Employee_irishRodger>();
for (int i = 0; i < numEmployees; ++i) {
    System.out.print("\nPlease enter the employee's name");
    String name = input.nextLine();
    System.out.print("\nPlease enter the employee's department");
    String dept = input.nextLine();
    System.out.print("\nPlease enter the employee's wage");
    String wage = input.nextLine();
    employees.add(new Employee_irishRodger(name, dept, wage));
}

我不知道类名Employee_irishRodger从何而来。为什么不只是Employee

于 2012-10-07T17:57:28.513 回答
1

Make name, dept and wage local.

于 2012-10-07T17:53:17.920 回答