0

我刚开始为了好玩而编写代码并尝试制作一个基本的计算器,但我遇到了一个问题。

底部有我的代码


import java.util.Scanner;

public class practice {

public static void main(String[] args) {
    double temp1, temp2;
    int temp4 = 1;
    int end = 0;
    **String temp3,temp5;**
    calculator cal = new calculator();
    Scanner scan = new Scanner(System.in);


    while(end==0){
    System.out.println("Please put your first number to calculate");
    temp1 = scan.nextDouble();
    System.out.println("Please put your second number to calculate");
    temp2 = scan.nextDouble();

    System.out.println("What arithmetic operation you want to do?(+,-,/,*)");

    **temp3 = scan.nextLine();**

    if(temp3.equals("+")){
        System.out.println("Result is" + cal.add(temp1, temp2));
    }

    else if(temp3.equals("-")){
        System.out.println("Result is" + cal.subtract(temp1, temp2));
    }

    else if(temp3.equals("*")){
        System.out.println("Result is" + cal.multiply(temp1, temp2));
    }

    else if(temp3.equals("/")){
        System.out.println("Result is" + cal.divide(temp1, temp2));
    }
    else
        System.out.println("You got wrong operator");

    while(temp4==1){
        System.out.println("Now you want to quit(press y/n)");
        temp5 = scan.nextLine();

        if(temp5.equals("y")){
            temp4=0;
            end=1;
        }

        else if(temp5.equals("n")){
            System.out.println("Then here we go again");
            temp4=0;
        }

        else
            System.out.println("You put wrong words");
        }
    }
}
}

我不明白为什么 temp3 不起作用。

我想检查我犯了错误,所以我做了 temp5 但它有效。

谁能解释为什么?

4

1 回答 1

1

问题是nextDouble()没有用完输入第二个时使用的换行符double。所以nextLine()看到换行符已经存在并使用它。

添加一个额外的nextLine()调用以使用第二个数字的换行符。

temp2 = scan.nextDouble();

// Add consuming of new line here.
String dummy = scan.nextLine();

System.out.println("What arithmetic operation you want to do?(+,-,/,*)");

temp3 = scan.nextLine();
于 2013-09-06T00:24:36.847 回答