0

I'm currently taking an Introduction to Java class where we are currently on Arrays topics. We have a class lab where are suppose to create a simple array program consisting a two classes (Passenger.java and Demo.java). The array can be of any sizing (minimum 4) and we can hard code details into few elements. We are supposed to create two methods for searching by the ID and name (firstname + lastname), and two methods for sorting (bubble & insertion) by the ID and surname in ascending order.

In my searching methods for both ID and name, I get java.lang.NullPointerException error when I entered a ID that does not exists in Array. It was suppose to return an error message that i have compose if it is not found.

In my sorting methods for ID, I also get java.lang.NullPointerException error after the second loop. For my sorting methods for surname, I don't know how to implement.

Hence may I know, how to solve this couple of issues with a working full code example.

Note:

Passenger.java

import java.util.Scanner;

public class Passenger {

    private String title;
    private String firstName;
    private String lastName;
    private long id;

    public Passenger() {

    }

    public Passenger(String title, String firstName, String lastName, long id) {
        this.title = title;
        this.firstName = firstName;
        this.lastName = lastName;
        this.id = id;
    }

    public void enterDetails() {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter your title: ");
        title = keyboard.next();
        System.out.print("Enter your first name: ");
        firstName = keyboard.next();
        System.out.print("Enter your last name: ");
        lastName = keyboard.next();
        System.out.print("Enter your ID: ");
        id = keyboard.nextLong();
    }

    public void outputDetails() {
        System.out.print();
        System.out.print("Passenger name: " + title + " " + firstName + " " + lastName);
        System.out.print("Identify Number: " + id);
        System.out.print();
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public long getId() {
        return id;
    }

}

Demo.java

import java.util.Scanner;

public class Demo {

    public static Passenger[] passengers = new Passenger[10];
    public static Scanner kb = new Scanner(System.in);

    public static void main(String[] args) {

        int option = 0;

        passengers[0] = new Passenger("Mr", "Benjamin", "Parker", 12345678);
        passengers[1] = new Passenger("Mrs", "Mary", "Long", 96421368);
        passengers[2] = new Passenger(....);
        passengers[3] = new Passenger(....);
        passengers[4] = new Passenger(....);
        passengers[5] = new Passenger(....);
        passengers[6] = new Passenger(....);
        passengers[7] = new Passenger(....);

        while(option != 7) {
            System.out.println("Please select an option:"
                + "\n1) Enter passenger particulars to array"
                + "\n2) Display passenger particulars from array"
                + "\n3) Search passenger particulars using ID"
                + "\n4) Search passenger particulars using both surname and name"
                + "\n5) Display passenger particulars in ascending order of ID"
                + "\n6) Display passenger particulars in ascending order of surname"
                + "\n7) Quit
            )
            option = kb.nextInt();

            switch(option) {
                case 1:
                    inputDetails();
                    break;
                case 2:
                    outputDetails();
                    break;
                case 3:
                    searchDetailsID();
                    break;
                case 4:
                    searchDetailsName();
                    break;
                case 5:
                    sortDetailsID();
                    break;
                case 6:
                    sortDetailsName();
                    break;
                case 7:
                    System.out.println("You quitted the program!");
                    break;
                default:
                    System.out.println("Invalid input!");
                    break;
            }
        }
    }

    public static void inputDetails() {
        int element = 0;
        for (int i = 0; i < passengers.length; i++) {
            if(passengers[i] != null)
                element++;
        }
        passengers[element] = new Passenger();
        passengers[element].enterDetails();
        element++;
    }

    public static void outputDetails() {
        for(int i = 0; i < passengers.length; i++) {
            passengers[i].outputDetails();
        }
    }

    public static void searchDetailsID() {
        boolean isFound = false;
        System.out.print("Please enter an passenger id: ");
        long id = kb.nextLong();

        for(int i = 0; i < passengers.length; i++) {
            if(id == passengers[i].getid()) {
                passengers[i].outputDetails();
                isFound = true;
                break;
            }
        }

        if(!isFound) {
            System.out.println("No passenger with that id!");
        }
    }

    public static void searchDetailsName() {
        boolean isFound = false;
        System.out.print("Please enter an passenger first name: ");
        String firstName = kb.next();
        System.out.print("Please enter an passenger last name: ");
        String lastName = kb.next();

        for(int i = 0; i < passengers.length; i++) {
            if(firstName.equalsIgnoreCase(passengers[i].getFirstName()) && lastName.equalsIgnoreCase(passengers[i].getLastName())) {
                passengers[i].outputDetails();
                isFound = true;
                break;
            }
        }

        if(!isFound) {
            System.out.println("No passenger with that name!");
        }
    }

    public static void sortDetailsID() {
        long temp = 0;
        for(int i = 0; i < passengers.length; i++) {
            for(int j = 0; j < passengers.length - 1; j++) {
                if(passengers[i].getId() > passengers[j].getId()) {
                    temp = passengers[i].getId();
                    passengers[i] = passengers[j];
                }
            }
        }
    }

    public static void sortDetailsName() {

    }

}
11
  • Please indicate which lines are throwing the NullPointerExceptions. Commented Apr 6, 2019 at 12:54
  • @Slaw I get NullPointerException when i entered a id that doesn't exists in the Arrays into searchDetailsID(), when i entered a firstName & lastName that doesn't exists in the Arrays into searchDetailsName(), and also the second for-loop in sortDetailsID. Please note that this is NOT because I use .... from passengers[2] to passengers[7]. Thanks Commented Apr 6, 2019 at 13:02
  • 1
    The stack trace of the NPE will tell you what line the exception is being thrown. Note that you initialize an array of length 10 but only fill indices 0 through 7 with a Passenger instance. That means indices 8 and 9 are null, yet you loop over the entire array as if none of the elements are null. If no ID or name match, you'll end up iterating over those null elements. Commented Apr 6, 2019 at 13:09
  • @Slaw alright noted. I solved the null error that happens in searchDetailsID() and searchDetailsName() by filling up indices 8 and 9. However, is it possible to provide me an answer on how to complete sortDetailsID() and sortDetailsName(). For sortDetailsID() i pretty sure it is wrong as i simply copy from youtube tutorial where they are using int as examples. Thanks Commented Apr 6, 2019 at 13:14
  • 1
    Your intention is to swap the elements, correct? That means you need to do passengers[i] = passengers[j] followed by passengers[j] = temp. That only works if temp is a Passenger. Commented Apr 6, 2019 at 13:37

1 Answer 1

1

Your NPE stack trace is :

Exception in thread "main" java.lang.NullPointerException
    at com.Demo.searchDetailsID(Demo.java:90)
    at com.Demo.main(Demo.java:46)

If you evaluate your code deeply, you will found that you initialized passengers array with 10 but you instance only 8 index in main method of Demo class. In other words, NPE is thrown when your loop wants to read the 9 or 10 index from the array. So if you replace the first line of Demo class with the following line, your code will work fine:

public static Passenger[] passengers = new Passenger[8];

Solution 2 :

Of course, you can use an if as following:

public static void searchDetailsID() {
        boolean isFound = false;
        System.out.print("Please enter an passenger id: ");
        long id = kb.nextLong();

        for(int i = 0; i < passengers.length; i++) {
            if(passengers[i] != null /* I append this check*/ && id == passengers[i].getId()) {
                passengers[i].outputDetails();
                isFound = true;
                break;
            }
        }

        if(!isFound) {
            System.out.println("No passenger with that id!");
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Regarding, "In other words, NPE is thrown when your loop wants to read the 9 or 10 index from the array": Arrays are zero-based. Since the array has a length of 10 the max index is 9, not 10.
Yes, I mean 8 or 9 indexes and in daily we called the 9 home or 10 home :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.