【问题标题】:Scanner input/output formatting wrong扫描仪输入/输出格式错误
【发布时间】:2019-11-08 16:42:46
【问题描述】:

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

这是期望的结果:

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

【问题讨论】:

  • 在while 循环之前有这两个console.next(); 有什么意义?

标签: java input output java.util.scanner


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多