1

Hey guys I'm trying to create a loop until a correct character choice is entered by the user. When I enter a wrong choice I get the error java.lang.NullPointerException. It might be with the way I'm inputing but I don't want to change that if I don't have to. choice is a private member of the class.

char wf() { 
    Scanner input = new Scanner(System.in); 
    System.out.println("What is your choice? (x/o)"); 
    choice = input.findInLine(".").charAt(0);

    while (choice != 'x' && choice != 'o') { 
        System.out.println("You must enter x or o!");
        choice = input.findInLine(".").charAt(0);
    }

    return choice; 
}//end wf
2
  • 1
    Is findLineAt returning null? If so, that's the problem, cause you call charAt right after. If findLineAt was null, you will not be able to call methods since there was no object to call methods from (instead there was null), hence the NPE. Commented Oct 11, 2015 at 17:14
  • 1
    Since it is clear that findLineAt returns null you only have to understand why. You can do that by reading the JavaDoc and by debugging this method, to see what happens there. Commented Oct 11, 2015 at 17:20

3 Answers 3

1

Change the function as below (I have tested this code):

char wf() { 
    Scanner input = new Scanner(System.in); 
    System.out.println("What is your choice? (x/o)"); 
    char choice = input.findInLine(".").charAt(0);

    while (choice != 'x' && choice != 'o') { 
        System.out.println("You must enter x or o!");
        choice = input.next().charAt(0);
    }

    return choice; 
}//end wf
Sign up to request clarification or add additional context in comments.

Comments

1

Check input.findInLine(".") to see if it null. If you don't have the expected input, it won't return anything..

Comments

1

change your code like below

char wf() { 
Scanner input = new Scanner(System.in); 
System.out.println("What is your choice? (x/o)"); 
if(input.findInLine(".") !=null){
choice = input.findInLine(".").charAt(0);
while (choice != 'x' && choice != 'o') { 
    System.out.println("You must enter x or o!");
    choice = input.findInLine(".").charAt(0);
 }
}
return choice; 
}//end wf

1 Comment

Can you explain why it should work, even though it doesn't?

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.