2014-11-23 47 views
0
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;   
    } 

} 

我试图把每个员工存储到数组,但所有员工的详细信息被用户输入的最后一个员工覆盖。你能帮忙吗?提前致谢!!JAVA雇员类型与阵列

+0

您正在循环中插入* same *'person',重写只是一种错觉。请将课程名称更改为以大写字母开头。 – Maroun 2014-11-23 12:20:22

+0

好的,谢谢你! – Gara 2014-11-23 12:43:16

回答

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的命名约定。

+0

哦,你太棒了!非常感谢! – Gara 2014-11-23 12:23:04