java项目贷款NullPointerException

时间:2015-06-25 02:30:35

标签: java arrays exception

任何人都可以帮我修复此异常吗?结果即将出现但仍然出现错误。还有其他四个类连接到它。

NPE

public class CreateLoans {
    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        int num;
        int term;
        int choice;
        String name;
        double amount;
        Loan[] w = new Loan[5];
        for (int i = 0; i < 1; i++) {
            System.out.println("Choose Loan Type: 1 Business Loan 2 Personal Loan");
            choice = s.nextInt();
            if (choice == 1) {
                System.out.print("Enter Loan Number: ");
                num = s.nextInt();
                System.out.print("Enter Last Name: ");
                s.nextLine();
                name = s.nextLine();
                System.out.print("Enter Loan Amount: ");
                amount = s.nextDouble();
                System.out.print("Enter Number of Terms: ");
                term = s.nextInt();
                w[i] = new BusinessLoan(num, name, amount, term);
            } else if (choice == 2) {
                System.out.print("Enter Loan Number: ");
                num = s.nextInt();
                System.out.print("Enter Last Name: ");
                s.nextLine();
                name = s.nextLine();
                System.out.print("Enter Loan Amount: ");
                amount = s.nextDouble();
                System.out.print("Enter Number of Terms: ");
                term = s.nextInt();

                w[i] = new PersonalLoan(num, name, amount, term);
            } else {
                System.out.println("Error, Please Enter 1 Or 2");
            }
        }
        for (int i = 0; i < w.length; i++) {
            System.out.println(w[i].toString());
        }
    }

}

1 个答案:

答案 0 :(得分:0)

不确定你想做什么:你的for循环中只创建了一个对象:

for (int i = 0; i < 1; i++) {// the code inside this loop only execute one time
   ...
}

但是你的数组中有五个元素Loan[] w = new Loan[5];

确定第二次循环时:

for (int i = 0; i < w.length; i++) {
    System.out.println(w[i].toString());
}

当我来到1时,w [i](w [1])将为空,所以当你调用w [i] .toString()时,你将获得NullPointerException

快速修复应更改为for (int i = 0; i < 1; i++)for (int i = 0; i < w.length; i++),并确保您输入的choice = s.nextInt();仅为12,或者仍然会有w数组

中间的空值