JAVA 员工类型与数组

标签 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;        
    }

}

我试图将每个员工存储到数组中,但所有员工的详细信息都被用户输入的最后一个详细信息覆盖。你能帮忙吗?提前致谢!!

最佳答案

数组中的所有元素都引用同一个 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 命名约定。

关于JAVA 员工类型与数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088857/

相关文章:

java - 内部类中的方法可以访问父类方法吗?

java - Spring Boot中@RequestMapping和Locale有什么关系?

c - 有符号整数的平台独立存储

python - 是否有内置方法从 Python 的所有基类中获取所有 __annotations__?

java - 非法参数异常 : Layout: -998896 < 0 in showcaseview

python - cython:将 2D numpy 数组传递给 cdef 函数

python - 如何使用 np.where() 创建特定行的新数组?

java - 创建一个方形的二维数组

types - 什么是 "vocabulary types",存在多少?

Java:相当于C++的const方法