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 /): ");





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




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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)