-1
        System.out.print("Hi " + name + ", which do you choose? (O)dds or (E)vens? ");

        String userChoice = null;

        while ((!userChoice.equals("O")) || (!userChoice.equals("E"))) {

            userChoice = input.nextLine();
        }

        if ( userChoice.equals("O") ) {
            System.out.println(name + " has picked odds! The computer will be evens.");
        } else {
            System.out.println(name + " has picked evens! The computer will be odds.");
        }

Cheers guys,

I am new to Java and I have no clue why this is not working. I want to ask the user for his choice until he chooses "O" or "E". Otherwise re-ask the user for his input. Therefore my idea was to check if userChoice does not equal "O" or "E" > ask again.

Thank you in advance for your help!

I get this error when running the code:

Let´s play a game called "Odds and Evens" What is your name? Ron Hi Ron, which do you choose? (O)dds or (E)vens? Exception in thread "main" > java.lang.NullPointerException at com.ronwalter.Main.main(Main.java:18) Process finished with exit code 1

Ron
  • 1
  • 1
  • 2
    because String userChoice = null in the first time – One Man Crew Aug 12 '20 at 11:03
  • 1
    Note that apart from the error you are currently getting your loop: `while ((!userChoice.equals("O")) || !(userChoice.equals("E")))` can only end in an infinite loop because your userChoice will always be not equal to at least one of your conditions that you linked with an or – OH GOD SPIDERS Aug 12 '20 at 11:05
  • Change String userChoise . The nullpointer ref to this as stated in the console as well. Also you have to end the loop somewhere. – egx Aug 12 '20 at 11:26

1 Answers1

0

because String userChoice = null

if String userChoice == null the while statement is:

while((!null.equals("O")) || (!null.equals("E")))

this is the reason that you get NullPointerException

The solution is the set userChoice to empty string:

    System.out.print("Hi " + name + ", which do you choose? (O)dds or (E)vens? ");

    String userChoice = "";<-------must set value!!!!

    while ((!userChoice.equals("O")) || (!userChoice.equals("E"))) {

        userChoice = input.nextLine();
    }

    if ( userChoice.equals("O") ) {
        System.out.println(name + " has picked odds! The computer will be evens.");
    } else {
        System.out.println(name + " has picked evens! The computer will be odds.");
    }
One Man Crew
  • 8,885
  • 2
  • 37
  • 50