Q:

Java calculator using switch case

My requirement - calc method should take two numbers from main, and calc will perform all the operations. Everything goes fine until a problem occurs in switch command. I get the error "choice cannot be resolved to a variable".
import java.util.Scanner;

public class Learn {

    public static void main(String args[]) {
        int firstnumber, secondnumber, choice;

        System.out.println("1- Add");
        System.out.println("2- Sub");
        System.out.println("3- Div");
        System.out.println("4- Mul");
        System.out.print("Enter your choice -");
        Scanner var = new Scanner(System.in);

        choice = var.nextInt();
        System.out.print("Enter first number -");
        firstnumber = var.nextInt();
        System.out.print("Enter second number -");
        secondnumber = var.nextInt();
        calc(firstnumber, secondnumber);
    }

    public static void calc(int x, int y) {
        int c;

        switch (choice) {
            case 1:
                c = x + y;
                System.out.print("Output-" + c);
                break;

            case 2:
                c = x - y;
                System.out.print("Output-" + c);
                break;

            case 3:
                c = x / y;
                System.out.print("Output-" + c);
                break;

            case 4:
                c = x * y;
                System.out.print("Output-" + c);
                break;
        }
    }
}

What am I missing, and how can I fix this?

A:

Since choice is a local in a different function, you need to pass it as a parameter:
public static void calc(int x, int y, int choice) {
    ...
}
...
calc (firstnumber,secondnumber, choice);

Note that your calc method is not optimal: all four cases have the same line in them:
System.out.print("Output-" + c);

You could move this line to after the switch, and add a default case to throw an exception when the choice is invalid.

