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

时间:2019-06-26 17:02:01

标签: java input output java.util.scanner

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

这是理想的结果:

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 个答案:

答案 0 :(得分:0)

完全在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);