2013-12-11 289 views
0
//employee class 
public class Employee { 


    //properties 
    private String name; 
    private int age; 
    private int salary; 


    //constructors 
    public Employee(String name,int age, int salary){ 
     this.name = name; 
     this.age = age; 
     this.salary = salary; 
    } 

    public Employee(Employee instance){ 
     name = instance.name; 
     age = instance.age; 
     salary = instance.salary; 
    } 

    //Methods 

    //getter and setter methods 
    public String getName(){ 
     return name; 
    } 
    public int getAge(){ 
     return age; 
    } 

    public int getSalary(){ 
     return salary; 
    } 

    public void setName(String name){ 
     this.name = name; 
    } 

    public void setAge(int age){ 
     this.name = name; 
    } 

    public void setSalary(int salary){ 
     this.salary = salary; 
    } 

    //toString 
    public String toString(){ 
     String result; 
     result = name + ", " + age + ", $" + salary; 
     return result; 
    } 
} 


//company management 
import java.util.Scanner; 
public class CompanyManagement { 

    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); 
     Employee[] employeeList; 
     employeeList = new Employee[20]; 
     String name; 
     int age; 
     int salary; 
     int choice; 
     int i; 

     i =0; 

     do{ 

      System.out.println("Welcome to the Company Management System. Please enter your choice" + "\n(1)Add Employee" + "\n(2)Delete Employee" + "\n(3)Change Employee Salary" + "\n(4)Exit" + "\nChoice: "); 
      choice = scan.nextInt(); 

      if(choice == 1) 
      { 

       System.out.println("Please enter employee name: "); 
       name = scan.nextLine(); 
       name = scan.nextLine(); 

       System.out.println("Please enter employee age: "); 
       age = scan.nextInt(); 

       System.out.println("Please enter employee salary: "); 
       salary = scan.nextInt(); 

       employeeList[i] = new Employee(name,age,salary); 


       for(int k = 0;k<=i;k++) 
        System.out.println(employeeList[i]); 
       i++; 

      } 

      if(choice == 2) 
      { 

      } 

      if(choice ==3) 
      { 

      } 


     }while(choice!=4); 
    } 
} 

爲什麼下面的代碼在循環重複時不會每次分配一個新引用,而是分配數組中所有索引的最後一個值。我該如何解決這個參考問題?將對象賦值給數組引用

employeeList[i] = new Employee(name,age,salary); 

回答

4

您的代碼正常工作。只是代替:

System.out.println(employeeList[i]); 

System.out.println(employeeList[k]); 
3
  for(int k = 0;k<=i;k++) 
       System.out.println(employeeList[i]); 

你在我循環k和索引。