在获取条目后,多态数组覆盖条目

时间:2014-03-07 10:37:05

标签: java arrays polymorphism

我有一个多态数组,用于存储从用户处获取的条目。当用户完成输入有效选项时,他们system.out.print数组以显示存储的详细信息。但这些细节最终都是重复阵列中的最后一个条目。

public static void main(String args[]) {
    System.out.println("\nWelcome to AIB Bank");
    System.out.println("___________________________");

    for(i = 0;i<5;i++){
        OverDraft = false;
        //prompt user for inputs and validate entries
        System.out.println("\nUser " + (i+1));
        System.out.print("Please enter name: ");
        name = input.next();
        System.out.print("\nPlease Enter Age: ");
        strAge = input.next();
        Age = Validate(strAge, 1, null);
        System.out.print("\nPlease Enter Salary: ");
        strSalary = input.next();
        Salary = Validate(strSalary, 2, null);
        System.out.print("\nPlease Enter Account Number: ");
        strAccNum = input.next();
        AccNum = Validate(strAccNum, 3, null);
        System.out.print("\nPlease Enter Balance: ");
        strBalance = input.next();
        Balance = Validate(strBalance, 4, null);
        System.out.print("\nIs This Person A Premium Customer(y/n): ");
        strodCheck = input.next();
        ODCheck = Validate(null, 5, strodCheck);
        if(ODCheck == 0){
            OverDraft = false;
        }//end if for overdraft
        else{
            OverDraft = true;
        }//end else for overdraft

        if(OverDraft == true){
            System.out.print("\nPlease Enter OverDraft Limit: ");
            strODLimit = input.next();
            ODLimit = Validate(strODLimit, 6, null);
        }//end if for ODLimit

        AccNums[i] = AccNum;

        if(OverDraft == true){
            PersonalDetails p1 = new PersonalDetails(name, Age);
            CustomerArray[i] = new PremiumCustomer(Salary, AccNum, Balance, OverDraft, ODLimit, p1);
        }
        else{
            PersonalDetails p1 = new PersonalDetails(name, Age);
            CustomerArray[i] = new Customer(Salary, AccNum, Balance, p1);
        }

        System.out.println(CustomerArray[i].toString());

    }//end for loop

    for(i=0;i<5;i++){
        System.out.println("\n" + i + "\n" + AccNums[i]);
        System.out.println(CustomerArray[i]);
    }

    login();

}//end main method

AccNum数组工作正常并显示正确的信息。

1 个答案:

答案 0 :(得分:2)

您的代码看起来像AgeSalary等变量都存储为数组中相同变量的引用,因此for循环的每次迭代实际上都访问相同的引用,因此最后,您在数组中有五个条目,它们指向内存中的相同值,而更改一个实际上会更改所有条目。尝试创建局限于for循环的局部变量来填充数组。