input character inside a while loop with validation
input character inside a while loop with validation
System.out.print("Enter the operator (+ - X /): ");
operator = input.next();
char c=operator.charAt(0);
while (c != '+' && c != '-' && c != '*' && c != '/')
System.out.println("Operator doesn't match. Try again.");
System.out.print("Enter the operator (+ - X /): ");
input.next().charAt(0);
Here, I want an input character value from keyboard which will be only symbols just (+ - * /) inside a while
loop. if the sign is not match the while loop will be running.
while
Here, the while
loop is working but the character is not checked. So, while loop continuously works with-
while
System.out.println("Operator doesn't match. Try again.");
System.out.print("Enter the operator (+ - X /): ");
2 Answers
2
You call a blank call to input.next().charAt(0);
but this does nothing but read the next character. c
is never changed so it always will be the invalid input. You need to resolve it back to c
:
input.next().charAt(0);
c
c
c = input.next().charAt(0);
In the last line of your while loop, you are retrieving an user input, but not storing it anywhere. You should do like that:
c = input.next().charAt(0);
If you want to do something fancy, you could also try using the do-while loop, like below:
char c;
do
System.out.println("Enter a operator (+ - * /):");
c = input.next().charAt(0);
while(c != '+' && c != '-' && c != '*' && c != '/');
That's true! Thanks for pointing it out, I already corrected it. I must be too tired, time to go to bed hahah
– Talendar
Aug 25 at 3:17
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
change 'input.next().charAt(0);' line inside the while loop to 'c=input.next().charAt(0);' it slove your issue. currently c value not change inside while loop
– janith1024
Aug 25 at 3:04