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
selection != "1"
is wrong. !=
checks for reference inequality ie 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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.