在Scanner中循环检查整数时,在第二次运行时激活两次

时间:2017-02-07 18:35:26

标签: java java.util.scanner

我的头衔有点差,但这就是问题所在。我使用Scanner类来获取2个输入,两个整数。如果一个不是整数,它会告诉用户输入另一个输入。这适用于第一个整数,但在第二个整数(和任何连续的整数)上,它会打印出两次文本。

代码:

public class Project1 {
    public static void main(String[] args) {
        // creates a new scanner
        Scanner scanner = new Scanner(System.in);

        // rejects input if the first token is not an integer
        System.out.println("Enter the first integer:");
        while(!scanner.hasNextInt()) {
            scanner.nextLine();
            System.out.println("That's not an integer, please enter again:");
        }
        // stores integer in variable when first token is an integer
        int num1 = scanner.nextInt();

        /* ======== repeats for second integer ======== */
        System.out.println("Enter the second integer:");
        while(!scanner.hasNextInt()) {
            scanner.nextLine();
            System.out.println("That's not an integer, please enter again:");
        }
        // stores integer in variable when first token is an integer
        int num2 = scanner.nextInt();

        System.out.println(num1 + num2);
    }
}

结果如下:

"Enter the first integer:"
>1.2
"That's not an integer, please enter again:"
>1
"Enter the second integer:"
>2.3
"That's not an integer, please enter again:"
"That's not an integer, please enter again:"
>2
"3"

为什么第二个整数重复两次?

1 个答案:

答案 0 :(得分:2)

不要使用nextLine()跳过该行,而是使用Scanner类的next()方法。

所以,现在以下代码工作正常。

import java.util.*;
public class Project1 {
    public static void main(String[] args) {
        // creates a new scanner
        Scanner scanner = new Scanner(System.in);

        // rejects input if the first token is not an integer
        System.out.println("Enter the first integer:");
        while(!scanner.hasNextInt()) {
           // scanner.nextLine();
            scanner.next();
            System.out.println("That's not an integer, please enter again:");
        }
        // stores integer in variable when first token is an integer
        int num1 = scanner.nextInt();

        /* ======== repeats for second integer ======== */
        System.out.println("Enter the second integer:");
        while(!scanner.hasNextInt()) {
            //scanner.nextLine();
            scanner.next();
            System.out.println("That's not an integer, please enter again:");
        }
        // stores integer in variable when first token is an integer
        int num2 = scanner.nextInt();

        System.out.println(num1 + num2);
    }
}

输出

Enter the first integer:
1.2
That's not an integer, please enter again:
2
Enter the second integer:
1.3
That's not an integer, please enter again:
3
5