Liondancer
Liondancer

Reputation: 16469

Null pointer exception in String[]

I am not sure why I am getting a NullPointerException on the line containing the while loop.

Originally when the String[] input is created. It is filled with null so maybe that is why I was getting the error. I tried to fix this by adding this bit of code to change that:

    for (String k : input) {
        k = "empty";
    }

This is probably the wrong approach so I am still getting the error.

code:

String[] input = new String[3];
        while(!input[0].equals("exit")) {
            Scanner sc = new Scanner(System.in);
            input = sc.nextLine().split(" ", 3);
            switch(input[0]) {
                // vi
                case "vi":
                    System.out.println("hi");
                    break;
                // ls
                case "ls":
                    break;
                // mkdir
                case "mkdir":
                    break;
                // pwd  
                case "pwd":
                    break;
            }   
        }

Upvotes: 0

Views: 49

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279940

This

for (String k : input) {
    k = "empty";
}

is effectively equivalent to

for (int i = 0; i < input.length; i++) {
    String k = input[i];
    k = "empty";
}

Changing the reference k does not affect the reference in the array.

Just do

for (int i = 0; i < input.length; i++) {
    input[i] = "empty";
}

I'm not sure what your while loop is meant to do so I will not comment on that.

Upvotes: 3

Related Questions