How would I get my program to quit when the user enters q? Is there something wrong with the scanner?
My code
import java.util.*;
public class Main{
public static void main(String []args){
int age;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your age, or enter 'q' to quit the program.");
age = scan.nextInt();
if(age.equals("q") || age.equals("Q")){
return 0;
}
System.out.println("Your age is " + age);
}
}
Advertisement
Answer
I can see mainly two problems in your code:
- It lacks a loop to repeat asking for age again. There can be many ways (
for,while,do-while) to write a loop but I finddo-whilemost appropriate for such a case as it always executes the statements within thedoblock at least once. ageis of type,intand therefore it can not be compared with a string e.g. your code,age.equals("q")is not correct. A good way to handle such a situation is to get the input into a variable of type,Stringand check the value if it should allow/disallow processing it (e.g. trying to parse it into anint).
Note that when you try to parse a string which can not be parsed into an int (e.g. "a"), you get a NumberFormatException which you need to handle (e.g. show an error message, change some state etc.).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int age;
String input;
Scanner scan = new Scanner(System.in);
boolean valid;
do {
// Start with the assumption that input will be valid
valid = true;
System.out.print("Enter your age, or enter 'q' to quit the program: ");
input = scan.nextLine();
if (!(input.equals("q") || input.equals("Q"))) {
try {
// Try to parse input into an int
age = Integer.parseInt(input);
System.out.println("Your age is " + age);
} catch (NumberFormatException e) {
System.out.println("Invalid input");
// Change the value of valid to false
valid = false;
}
}
} while (!valid || !(input.equals("q") || input.equals("Q")));
}
}
A sample run:
Enter your age, or enter 'q' to quit the program: a Invalid input Enter your age, or enter 'q' to quit the program: 12.5 Invalid input Enter your age, or enter 'q' to quit the program: 14 Your age is 14 Enter your age, or enter 'q' to quit the program: 56 Your age is 56 Enter your age, or enter 'q' to quit the program: q