首页 > 解决方案 > 扫描仪输入/输出格式错误

问题描述

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

这是期望的结果:

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);

标签: javainputoutputjava.util.scanner

解决方案


完全删除console.next()之前的while循环,你不需要它。然后,您将获得所需的输出。当您拥有 时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);

推荐阅读