簡體   English   中英

循環重新啟動時,為什么我的第一個打印語句打印兩次?

[英]Why does my first print statement print twice when the loop restarts?

當我輸入第一個或第二個數字值的無效輸入時"Enter an operation (+, -, *, /, quit)"為什么"Enter an operation (+, -, *, /, quit)"打印兩次? "Enter an operation (+, -, *, /, quit)"無效后"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;
        }

    }

}

使用Scanner.nextInt()等會使掃描器緩沖區保持打開狀態,因為它不會占用整行,而是僅將最接近的原始值和該行的其余部分存儲在掃描器緩沖區中,並且僅由新的行調用使用。 這會導致很多意外情況,並且難以解決錯誤。

使用掃描儀獲取原始數據類型時的更好做法是使用

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

這樣一來,掃描程序就消耗了整行,並且緩沖區中沒有存儲任何內容,而且您不會因輸出/輸入流出現異常而感到頭疼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM