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() {

    }

}
papert1ger
  • 59
  • 5
  • Please indicate which lines are throwing the `NullPointerException`s. – Slaw Apr 06 '19 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 – papert1ger Apr 06 '19 at 13:02
  • 1
    The [stack trace](https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) 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. – Slaw Apr 06 '19 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 – papert1ger Apr 06 '19 at 13:14
  • Another option to filling up the entire array is keeping a record of the actual "size" of the array. The size would be the last non-null index + 1 (e.g. if all indices contain non-null elements then size = 10). Make sure there are no "gaps" in the array using this approach. Regarding `sortDetailsID()`, shouldn't `temp` be a `Passenger`? Regarding `sortDetailsName()`, see [the documentation of `String.compareTo(String)`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/String.html#compareTo(java.lang.String)). – Slaw Apr 06 '19 at 13:25
  • Java compiler even can't compile your code so how do you get NPE? Where is `getStudentNo` method in `Passenger` class ? Why `getId` method was written as `getid` in `Demo` class? You must correct this compile time error then you can ask about semantic or NPE. – Sam Apr 06 '19 at 13:28
  • @Sam oops my apologies! have updated the coding. – papert1ger Apr 06 '19 at 13:31
  • @Slaw do you mean changing `long temp = 0` to `Passenger temp` on line 1 and `temp = passengers[i]` on line 4 of `sortDetailsID()`? – papert1ger Apr 06 '19 at 13:34
  • 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`. – Slaw Apr 06 '19 at 13:37
  • Your code isn't clear. Compile your code and then post here. What is `undergraduate` array? – Sam Apr 06 '19 at 13:38
  • @Sam my apologies. i edited my code around 10 mins ago. could you kindly refresh the page. thanks a lot – papert1ger Apr 06 '19 at 13:44

1 Answers1

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!");
        }
    }
Sam
  • 6,770
  • 7
  • 50
  • 91
  • 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. – Slaw Apr 06 '19 at 14:16
  • Yes, I mean 8 or 9 indexes and in daily we called the 9 home or 10 home :) – Sam Apr 06 '19 at 14:24