为什么我的第一个print语句在循环重启时打印两次?

时间:2015-10-22 20:28:33

标签: java

为第一个或第二个数值输入无效输入时,为什么"Enter an operation (+, -, *, /, quit)"打印两次?在无效输入后,循环应该重新启动并打印"Enter an operation (+, -, *, /, quit)"

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    int i = 1;
    while(i > 0){
        String operation = "";
        int firstInt = 0;
        int secondInt = 0;
        double firstDouble = 0.0;
        double secondDouble = 0.0;
        int intAnswer = 0;
        double answer = 0.0;
        boolean first = false;
        boolean second = false;

        System.out.println("Enter an operation (+, -, *, /, quit)");
        operation = scnr.next();
        if(operation.equals("+")|| operation.equals("-") || operation.equals("*") || operation.equals("/")){
            System.out.println("Enter first numeric value");
            if(scnr.hasNextInt()){
                firstInt = scnr.nextInt();
                first = true;
            }else if(scnr.hasNextDouble()){
                firstDouble = scnr.nextDouble();
            }
            else{
                continue;
            }
            System.out.println("Enter second numeric value");
            if(scnr.hasNextInt()){
                secondInt = scnr.nextInt();
                second = true;
            }else if(scnr.hasNextDouble()){
                secondDouble = scnr.nextDouble();
            }
            else{
                continue;
            }
        }
        else if(operation.equals("quit")){
            System.exit(0);
            scnr.close();
            break;
        }

    }

}

1 个答案:

答案 0 :(得分:0)

使用Scanner.nextInt()等使扫描仪缓冲区保持打开状态,因为它不会消耗整行,但只有最近的原始值,而行的其余部分存储在扫描仪缓冲区中,只有新的才能使用线路电话。这导致了很多意想不到的问题并且难以解决错误。

使用扫描仪获取原始数据类型时更好的做法是使用

double yourDouble = Double.parseDouble(Scanner.nextLine());
//for int you use Integer.parserInt(Scanner.nextLine()

这样扫描仪就会消耗整条生产线,并且没有任何内容存储在缓冲区中,您也不会因行为不端的输出/输入流而头疼。