当用户输入q时,我该如何退出程序?扫描仪有什么问题吗?
我的代码
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);
}
}
我可以在您的代码中看到主要两个问题:
- 它缺少一个循环来重复询问年龄。可以有很多方法(
for
、while
、do-while
(来编写循环,但我发现do-while
最适合这种情况,因为它总是至少执行do
块中的语句一次 age
的类型为int
,因此无法将其与字符串进行比较,例如您的代码age.equals("q")
不正确。处理这种情况的一个好方法是将输入输入到类型为String
的变量中,并检查该值是否允许/不允许处理它(例如,试图将其解析为int
(
请注意,当您试图解析一个无法解析为int
(例如"a"
(的字符串时,您会得到一个需要处理的NumberFormatException
(例如显示错误消息、更改某些状态等(。
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")));
}
}
样本运行:
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