将对象分配给数组引用

时间:2013-12-11 14:22:53

标签: java

//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); 

2 个答案:

答案 0 :(得分:4)

您的代码运行正常。而不是:

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

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

答案 1 :(得分:3)

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

您正在循环k并在i上编制索引。