【发布时间】:2020-04-12 19:58:57
【问题描述】:
我知道有人问过这个问题,但我尝试应用我在此处看到的内容并收到错误。
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
boolean is_int = false;
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) {
// If the input isn't an int, the loop is supposed to run
// until an int is input.
get_input.hasNextInt();
year_of_birth = get_input.nextInt();
}
//year_of_birth = get_input.nextInt();
System.out.println("Enter the current year");
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();
}
}
没有循环,一切正常。我的代码有什么问题?为了清楚起见,我试图要求输入,直到输入可以被验证为整数。
非常感谢。
【问题讨论】:
-
那个 wgile 循环没有意义
-
正如 Antoniossss 所提到的,使用该循环您不会有任何收获。您正在做的是要求扫描仪将字符串解析为 int only 如果无法解析。尝试删除该感叹号或澄清您要执行的操作。
-
在循环中,我想检查输入是否为整数,然后将其分配给int year_of_birth。我得到:“线程“主”java.util.InputMismatchException 中的异常”。我尝试使用布尔值作为中间值,然后将 hasNextInt 的结果分配给布尔值,但我无法做到。
-
而你正在做 while(输入不是整数) => 分配整数。
-
我正在尝试“当(输入不是整数)尝试请求新输入并测试这是否是整数”。不知道是不是很清楚。