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


#1



Replace this line with your code.


#2

First you need to create the scanner

Scanner scanner = new Scanner( System.in );

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") {
System.exit(0);
} 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.


#3

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