Cant figure out java while loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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 )

19th Aug 2018, 3:35 PM
Nick Johnson
Nick Johnson - avatar
6 Answers
+ 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; }
19th Aug 2018, 6:27 PM
Ipang
+ 3
could you post your code here so we can see exactly what is happening? that would be the easiest.
19th Aug 2018, 3:48 PM
Robert Atkins
Robert Atkins - avatar
+ 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; }
19th Aug 2018, 6:26 PM
Ipang
+ 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
21st Aug 2018, 2:09 AM
Nick Johnson
Nick Johnson - avatar
+ 1
Nick Johnson Sorry mate, I forgot to wrap the conditions in parentheses, I'll update the first alternative now, my bad :D
21st Aug 2018, 7:05 AM
Ipang
0
I updated so the full method is there now.
19th Aug 2018, 3:56 PM
Nick Johnson
Nick Johnson - avatar