I'm learning java and I wrote this program and it compiled successfully on my college computer but not compiling on my home pc.can any one help me?
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;
}
}
This is the error I'm getting :
Calculator.java:23: incompatible types
found : java.lang.String
required: int
switch (operator){ ^
1 error
Using switch
on a String
was introduced in Java 7. Make sure you're using JDK7+ on the other machine to compile the program.
As mentioned in the comments, if you can't upgrade the JDK for some reason, you can use a char
instead:
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;
...