我的要求 - calc
方法應該從main
開始取兩個數字,calc
將執行所有操作。一切都很順利,直到switch
命令發生問題。我收到錯誤「選擇無法解析爲變量」。使用開關盒的Java計算器
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;
}
}
}
我在想什麼,我該如何解決這個問題?
'choice'是** **局部變量in'main' ... – 2014-11-01 20:06:51
一個函數中的代碼在另一個函數中看不到局部變量。 – khelwood 2014-11-01 20:07:15
請記住,在問題中發佈代碼時,您的所有代碼都需要縮進4個空格。你沒有那樣做。 – 2014-11-01 20:07:49