0

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;
            }   
        }
2

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.