public static void main(String[] args) {
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your name: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
int n = reader.nextInt();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your email: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
}
如果用户在Enter your age
下放置了除数字以外的任何其他内容,我该如何说明输入不正确并再次询问?
答案 0 :(得分:1)
您可以获取用户提供的行,然后使用Integer.parseInt(String)
中的do/while loop
解析该行:
Scanner reader = new Scanner(System.in);
Integer i = null;
// Loop as long as i is null
do {
System.out.println("Enter your age: ");
// Get the input from the user
String n = reader.nextLine();
try {
// Parse the input if it is successful, it will set a non null value to i
i = Integer.parseInt(n);
} catch (NumberFormatException e) {
// The input value was not an integer so i remains null
System.out.println("That's not a number!");
}
} while (i == null);
System.out.println("You chose: " + i);
一种更好的方法,可以避免根据https://stackoverflow.com/a/3059367/1997376捕获Exception
。
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
// Iterate as long as the provided token is not a number
while (!reader.hasNextInt()) {
System.out.println("That's not a number!");
reader.next();
System.out.println("Enter your age: ");
}
// Here we know that the token is a number so we can read it without
// taking the risk to get a InputMismatchException
int i = reader.nextInt();
System.out.println("You chose: " + i);
答案 1 :(得分:0)
- 无需经常声明变量扫描仪,只需一次
- 关注字符串
醇>nextLine();
;提出空白问题,建议.next();
使用do-while
do
{
//input
}
while(condition);//if it is true the condition returns to do otherwise leaves the cycle
使用块try{ .. }catch(Exception){..}
捕获异常不匹配 - 输入类型异常是当输入不是我在预期的情况下在预期数字时输入字母
Scanner reader = new Scanner(System.in);
int n=0;
do
{
System.out.println("Enter your age: ");
try {
n = reader.nextInt();
}
catch (InputMismatchException e) {
System.out.print("ERROR NOT NUMBER");
}
}
while(n<0 && n>100);//in this case if the entered value is less than 0 or greater than 100 returns to do
System.out.println("You chose: " + n);