我正在学习java,我编写了这个程序,它在我的大学计算机上成功编译,但没有在我的家用电脑上编译。任何人帮助我吗?
import java.util.Scanner;
public class Calculator{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please Enter 2 Values");
int userInput1 = input.nextInt();
int userInput2 = input.nextInt();
System.out.println("Please Enter an Operation");
String operator = input.next();
if(operator == null){
return;
}
int answer = 0;
switch (operator){
case "+":
answer = Add(userInput1,userInput2);
break;
case "*":
answer = Multiply(userInput1,userInput2);
break;
case "-":
answer = Subtract(userInput1,userInput2);
break;
case "/":
answer = Divide(userInput1,userInput2);
break;
default:
System.out.println("Invalid Operator");
System.exit(0);
break;
}
System.out.println("The answer is " + answer);
}
public static int Add(int num1, int num2)
{
return num1 + num2;
}
public static int Subtract(int num1, int num2)
{
return num1 - num2;
}
public static int Multiply(int num1, int num2)
{
return num1 * num2;
}
public static int Divide(int num1, int num2)
{
return num1 / num2;
}
}
这是我得到的错误:
Calculator.java:23:不兼容的类型
发现:java.lang.String
必需:int
switch (operator){ ^
1错误
答案 0 :(得分:7)
在Java 7中引入了在switch
上使用String
。确保在其他计算机上使用JDK7 +来编译程序。
如评论中所述,如果由于某种原因无法升级JDK,则可以使用char
代替:
String operator = input.next();
if(operator == null || operator.isEmpty()) {
return;
}
int answer = 0;
switch (operator.charAt(0)) {
case '+':
answer = Add(userInput1, userInput2);
break;
case '*':
answer = Multiply(userInput1, userInput2);
break;
...