有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java扫描仪输入/输出格式错误

此代码返回正确的最终结果,但控制台中输入和输出的格式不正确

以下是期望的结果:

Type your age: hello
Type your age: ?
Type your age: 3.14
Type your age: 25
Type your GPA: a
Type your GPA: bcd
Type your GPA: 2.5
age = 25, GPA = 2.5

该程序不断分别询问年龄和GPA,直到得到正确的输入,然后打印出来

以下是我得到的:

Type your age: hello
Type your age: ?
Type your age: 3.14
25
Type your GPA: a
Type your GPA: bcd
2.5
age = 25, GPA = 2.5

正如您所见,结果相同,但格式不正确。我确信这与我使用扫描器对象的方式有关,但我对扫描器的理解目前有限

下面是简单的代码:

Scanner console = new Scanner(System.in);
System.out.print("Type your age: ");
console.next();
while (!console.hasNextInt()) {
  System.out.print("Type your age: ");
  console.next();
}
int age = console.nextInt();

System.out.print("Type your GPA: ");
console.next();
while (!console.hasNextDouble()) {
  System.out.print("Type your GPA: ");
  console.next();
}
double gpa = console.nextDouble();
System.out.println("age = " + age + ", GPA = " + gpa);

共 (1) 个答案

  1. # 1 楼答案

    完全删除while循环之前的console.next(),您不需要它。然后您将获得所需的输出。当您拥有console.next()时,您正在寻找并返回另一个完整的令牌,这在您的情况下并不需要

            Scanner console = new Scanner(System.in);
            System.out.print("Type your age: ");
            while (!console.hasNextInt()) {
                System.out.print("Type your age: ");
                console.next();
            }
    
            int age = console.nextInt();
    
            System.out.print("Type your GPA: ");
    
            while (!console.hasNextDouble()) {
                System.out.print("Type your GPA: ");
                console.next();
            }
    
            double gpa = console.nextDouble();
            System.out.println("age = " + age + ", GPA = " + gpa);