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;
}
}
我试图将每个员工存储到数组中,但所有员工的详细信息都被用户输入的最后一个详细信息覆盖。你能帮忙吗?提前致谢!!
最佳答案
数组中的所有元素都引用同一个 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 ();
}
顺便说一句,我建议您将类名更改为 Person
或 PersonType
以符合 Java 命名约定。
关于JAVA 员工类型与数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088857/