+ 1
Cant figure out java while loop
Public static String userMove(){ Scanner input = new Scanner(System.in); System.out.print("Where would you like to move? (R, L, U, D)"); String selection = input.next(); while ( !selection.equalsIgnoreCase("r") || !selection.equalsIgnoreCase("l") || !selection.equalsIgnoreCase("u")|| !selection.equalsIgnoreCase("d")) { System.out.print("Please choose either (R, L, U, D)"); userMove(); } return selection; } im trying to get the test to repeat itself until either r l u or d is selected and when one of those are selected it still repeats itself over and over please help! ( userMove(); is the method its contained in to call itself )
6 ответов
+ 3
// Alternative using contains method
public static String userMove(){
Scanner input = new Scanner(System.in);
System.out.print("Where would you like to move? (R, L, U, D)");
String selection = input.next();
// Here we check if 'selection' is a substring of "rlud".
// I guess this is somewhat more readable.
while(!"rlud".contains(selection.toLowerCase()))
{
System.out.println("Please choose either (R, L, U, D)");
selection = input.next();
}
return selection;
}
+ 3
could you post your code here so we can see exactly what is happening? that would be the easiest.
+ 2
Nick Johnson the condition you passed to the while loop was incorrect, and you call UserMove again inside loop body. I would rather suggest to re-read the 'selection' input inside loop body, as follows;
public static String userMove(){
Scanner input = new Scanner(System.in);
System.out.print("Where would you like to move? (R, L, U, D)");
String selection = input.next();
// Use the ! operator only in the beginning, not on each operand
while (!(selection.equalsIgnoreCase("r") || selection.equalsIgnoreCase("l") || selection.equalsIgnoreCase("u") || selection.equalsIgnoreCase("d"))) {
System.out.print("Please choose either (R, L, U, D)");
// Here read the 'selection' input again, instead of calling UserMove
selection = input.next();
}
return selection;
}
+ 1
I got the alternative one to work but for some reason with the other one the only one that would work is if i selected "r" if not, it would forever just keep asking for input
+ 1
Nick Johnson Sorry mate, I forgot to wrap the conditions in parentheses, I'll update the first alternative now, my bad :D
0
I updated so the full method is there now.