2014-11-01 54 views
0

我的要求 - 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; 
     } 
    } 
} 

我在想什麼,我該如何解決這個問題?

+0

'choice'是** **局部變量in'main' ... – 2014-11-01 20:06:51

+0

一個函數中的代碼在另一個函數中看不到局部變量。 – khelwood 2014-11-01 20:07:15

+0

請記住,在問題中發佈代碼時,您的所有代碼都需要縮進4個空格。你沒有那樣做。 – 2014-11-01 20:07:49

回答

4

由於choice處於不同功能的地方,你需要把它作爲參數傳遞:

public static void calc(int x, int y, int choice) { 
    ... 
} 
... 
calc (firstnumber,secondnumber, choice); 

請注意,您calc方法不是最佳的:所有四個case■找同一線路在其中:

System.out.print("Output-" + c); 

你可以此線移動到switch後,並添加默認情況下拋出一個異常時,選擇的是無效的。

+1

同意將所有'case'塊中的通用語句分解出來。接得好。 – J0e3gan 2014-11-01 20:13:15

0

您將需要通過choice作爲參數傳遞給calc如果你想在calc使用它的價值 - 像這樣的調整對您的代碼:

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(choice, firstnumber, secondnumber); // 3rd arg added for choice 
    } 

    public static void calc(int choice, int x, int y) { // 3rd param added for choice 
     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; 
     } 
    } 
}