-2

Can anyone help me fix this exception? The Results coming up but still getting the error. There are four other classes connected to it.

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

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366

1 Answers1

0

Not sure what do you want to do: you have only one object created since your for loop is:

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

But you have five elements in your array Loan[] w = new Loan[5];

sure when the second loop:

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

when i comes to 1, the w[i] (w[ 1 ]) will be null, so when you call w[i].toString(), you will get a NullPointerException

Quick fix should be change for (int i = 0; i < 1; i++) to for (int i = 0; i < w.length; i++) and make sure choice = s.nextInt(); you are entering only is 1 or 2, or there still will be a null value in the middle of w array

JaskeyLam
  • 15,405
  • 21
  • 114
  • 149