-2

I'm trying to create a method to validate a user input to be "1". Therefore I used a while loop for validation. Yet, it enters the while loop when the input is "1".

public static int switchInput() {

    System.out.print("\n" + "Enter your selection: ");

    Scanner userInput = new Scanner(System.in);
    String selection = userInput.next();

    while (selection != "1" /*&& selection != "2" && selection != "3"*/){

        System.out.println("Enter 1: ");
        //System.out.println("Please enter either '1','2' or '3': ");
        selection = userInput.next();

    }

    int result = Integer.parseInt(selection);
    return result;
}

Output:

What would you like?
1: Regular Hamburger
2: Healthy Burger
3: Deluxe Burger

Enter your selection: 
1
Enter 1: 
1
Enter 1: 
1
Enter 1: 

Process finished with exit code -1
Naman
  • 27,789
  • 26
  • 218
  • 353
Lord Heffe
  • 13
  • 2
  • 1
    !selection.equals("1") use this instead of selection != "1". – Rax Dec 29 '18 at 08:44
  • Possible duplicate of [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – MC Emperor Dec 29 '18 at 09:22

2 Answers2

1

selection != "1" is wrong. != checks for reference inequality i.e. if the objects on both sides are not same, then the condition will return true.

In your case, selection and String object with value 1 are different objects, that's why the condition is returning true.

Instead, use !selection.equals("1")

Edit:

As suggested by Igor Nikolaev, if there is no compulsion of using String object as a choice, you could use int selection = userInput.nextInt() for getting selection as int. In that case, you can use selection == 1.

Kunal Puri
  • 3,419
  • 1
  • 10
  • 22
0

You see, the variable 'selection' is a string, and to compare two string using != is incorrect. Instead, use the method equals() So I see you want to compare the String selection and a string "1" replace the if condition with:

while(!selection.equals("1")){

TIP: You expect the user to input a number, so why make selection a string? It would be better if it was an int.