How to convert input string to number and if user input q or Q then close the program


<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>


Replace this line with your code.

<do not remove the three backticks above>

First you need to create the scanner

Scanner scanner = new Scanner( );

Print your user prompt to the console, then the next line of code should create a new string for the user’s input.

String input = scanner.nextLine();

Then just use an if statement to test for the letter q, and if not q, try to cast to an integer.

if input.toLowerCase().Equals(“q”) {
} else {
int inputNum = Integer.parseInt(input);

That should do what you want.

Be aware though, this will just throw an error if your user inputs something other than a number or the letter q. You’d have to wrap the integer casting in a try/catch in order to prevent that, which would also necessitate you wrap the whole thing in a method. I don’t know how complicated you want to get with this, so I won’t go into detail on this. If you’re just trying to get through the java course, the above should be all you need to know.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.