我刚开始编码以获得乐趣,并试图制作一个基本的计算器, 但我遇到了问题。
底部有我的代码
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但它确实有效。
任何人都可以解释原因吗?
答案 0 :(得分: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();