【问题标题】:java project loans NullPointerException [duplicate]java项目贷款NullPointerException [重复]
【发布时间】:2015-06-25 02:30:34
【问题描述】:

谁能帮我解决这个异常?结果出现但仍然出现错误。还有其他四个与之相关的类。

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());
        }
    }

}

【问题讨论】:

  • 如果您突出显示 CreateLoans 类的第 56 行的代码会有所帮助

标签: java arrays exception


【解决方案1】:

不确定你想做什么:你只创建了一个对象,因为你的 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());
}

当 i 到 1 时,w[i] (w[ 1 ]) 将为空,所以当你调用 w[i].toString() 时,你会得到一个NullPointerException

快速修复应该将for (int i = 0; i &lt; 1; i++)更改为for (int i = 0; i &lt; w.length; i++)并确保您输入的choice = s.nextInt();仅是12,否则w数组中间仍然会有一个空值

【讨论】:

    猜你喜欢
    • 2021-09-07
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多