带有数组的JAVA员工类型

时间:2014-11-23 12:18:55

标签: java arrays types

package javaapplication2;
import java.util.Scanner;

public class JavaApplication2 
{
    public static void main(String[] args) 
    {
       person_type salespeople[] = new person_type [100];
       person_type person = new person_type();
       int counter = 0;

       person.gross=0;
       person.salary=0;

       System.out.println("How many workers are there?");
       Scanner number_of_workers = new Scanner(System.in);
       counter=number_of_workers.nextInt();

       for(int i=0; i<counter; i++)
       {
           salespeople[i] = person;
           System.out.println(person.salary);
       }

       for(int i=0; i<counter; i++)
       {
           System.out.print("Enter the salary of the salesperson ");
           System.out.print(i+1); 
           System.out.println(":");
           Scanner salary = new Scanner(System.in);
           salespeople[i].salary = salary.nextInt();  


           System.out.print("Enter the gross of the salesperson ");
           System.out.print(i+1); 
           System.out.println(":");
           Scanner gross = new Scanner(System.in);

           salespeople[i].gross = gross.nextInt(); 

           System.out.println("1---- " + salespeople[0].salary);
           System.out.println(i);
       }

        System.out.println("First worker's salary is: " + salespeople[0].salary);
        System.out.println("First worker's gross " + salespeople[0].gross);

        System.out.println("Second worker's salary is: " + salespeople[1].salary);
        System.out.println("Second worker's gross is: " + salespeople[1].gross);
    }

    private static class person_type
    {
        int salary;
        int gross;        
    }

}

我正在尝试将每个员工存储到阵列中,但所有员工的详细信息都会被用户输入的最后一个员工覆盖。你能帮忙吗?在此先感谢!!

1 个答案:

答案 0 :(得分:3)

数组中的所有元素都引用相同的person_type实例:

for(int i=0; i<counter; i++)
{
    salespeople[i] = person;
    System.out.println(person.salary);
}

您必须为数组的每个索引创建一个新的person_type实例。

for(int i=0; i<counter; i++)
{
    salespeople[i] = new person_type ();
}

顺便说一句,我建议您将类名更改为PersonPersonType以符合Java命名约定。