I’m having the error Cannot resolve symbol for x on line 22 of my program.
if (choice == 1) {
System.out.print(add(x, y));
Is this a scope issue or am I missing something?
I know my if statement isn’t complete, but I thought I’d get the addition working first and then work on the rest.
import java.util.Scanner;
class calculator {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter from the following Choices");
System.out.println("1 - Add");
System.out.println("2 - Subtract");
System.out.println("3 - Multiply");
System.out.println("4 - Subtract");
System.out.println("Enter an operator");
int choice = scan.nextInt();
System.out.println("Enter first number");
scan.nextInt();
System.out.println("Enter Second Number");
scan.nextInt();
if (choice == 1) {
System.out.print(add(x, y));
}
}
public static int add ( int x, int y){
int total;
total = x + y;
return total;
}
public static int subtract ( int x, int y){
int total;
total = x - y;
return total;
}
public static int multiply ( int x, int y){
int total;
total = x * y;
return total;
}
public static int divide ( int x, int y){
int total;
total = x / y;
return total;
}
}
>Solution :
In your main you haven’t declared an x int variable nor a y var. When you’re trying to pass those non-existing variables to your add method the compiler shows you the error "cannot resolve symbol x" because it doesn’t know what you’re referring to.
Your nextInt() calls are happening but they’re not storing any value anywhere. You should rewrite your main like this:
class calculator {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter from the following Choices");
System.out.println("1 - Add");
System.out.println("2 - Subtract");
System.out.println("3 - Multiply");
System.out.println("4 - Subtract");
System.out.println("Enter an operator");
int choice = scan.nextInt();
System.out.println("Enter first number");
int x = scan.nextInt();
System.out.println("Enter Second Number");
int y = scan.nextInt();
if (choice == 1) {
System.out.print(add(x, y));
}
}
//... rest of your code ...
}