我想知道是否有人能看到我的代码有什么问题。它的工作原理除了程序没有确认我的switch语句 - 我搜索了很多问题,但由于我是新手,我显然遗漏了一些东西。
import java.util.Scanner;
class Calmlr1 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String anotherOption = "y", operatorOpt= "a";
int no1=0, no2=0;
double result= 0;
System.out.println ("Welcome to the online calculator! Let's begin...");
while (anotherOption.equalsIgnoreCase ("y")) {
System.out.println ("Please enter your 1st number: ");
no1 = input.nextInt();
System.out.println ("Please confirm your operator:\n1 = +\n2 = - \n3 = *\n4 = /");
operatorOpt = input.next ();
System.out.println ("Please enter your 2nd number: ");
no2 = input.nextInt();
switch(no1) {
case 1:
result=no1+no2;
break;
case 2:
result=no1-no2;
break;
case 3:
result=no1*no2;
break;
case 4:
result=no1/no2;
default:
result = 0 ;
break;
}
System.out.println("Your total calculation is: "+result);
System.out.println("Would you like to do another sum? y/n ");
anotherOption=input.next();
}
}
}
答案 0 :(得分:3)
您应该使用switch(operatorOpt)
。现在你正在打开第一个数字。
您还需要更改:
int operatorOpt= 0;
operatorOpt = input.nextInt();
也就是说,如果你想让你的switch语句保持不变。另请参阅@Daniel Imms答案以获取其他错误修复。
答案 1 :(得分:2)
尝试在break
case 4
case 4:
result=no1/no2;
break;
编辑 J的答案是主要问题,但这是另一个会破坏分裂的问题。
答案 2 :(得分:1)
您的switch
应位于operatorOpt
而不是no1
。
此外,您在break
中遗漏了case 4
。所以,如果你想进行分工,你将获得0
作为结果。
operatorOpt
用户的输入应使用input.nextLine()
完成。或者,如果您希望使用switch
保持相同的input.nextInt()
语句。
应该是这样的:
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}
答案 3 :(得分:0)
您的switch语句应该位于“operatorOpt”而不是“no1”,因为您要检查操作员并根据您要进行的计算。但是,必须使用JDK1.7在Switch语句中使用String,因为以前版本的JDK不支持String Switch。 此外,您应该在案例4中使用“break”。
答案 4 :(得分:0)
您的开关应该在operatorOpt上,而不是在no1上。
你可以这样使用
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}