有没有办法从其他方法访问开关盒?

时间:2019-04-07 19:53:50

标签: java switch-statement

我正在开发一个数学测验程序,该程序将询问用户是否想要加法,减法,除法或乘法测验。因此,通过使用switch case语句,我可以访问该方法吗?

public static void Addition(){ 

} 

public static void Subtraction(){

} 

public static void Division(){ 

} 

Public static void Multi(){

} 

static void option(){
        Scanner input = new Scanner(System.in);
            int choice = 0; 

        System.out.print("Enter your choice: ");
    choice = input.nextInt(); 

switch (choice){ 
            case 1: 
                break; 
            case 2: 
                break; 
            case 3: 
                break; 
            case 4: 
                break; 
            default: 
                                break;
}

2 个答案:

答案 0 :(得分:0)

正确的语法例如为:

switch (choice){ 
        case 1:
            Addition();
            break; 
        case 2: 
            Subtraction();
            break; 
        case 3: 
            Division();
            break; 
        case 4: 
            Multi();
            break; 
        default: 
            break;
}

我建议通常使用camelcase

在Java中命名方法

答案 1 :(得分:0)

我认为您真的想要这样的东西:

public static double add(double x, double y){ 
  return x + y;
} 

public static double subtract(double x, double y){
  ...
} 

public static void divide(double x, double y){ 
  ...    
} 

public static double multiply(double x, double y){
  ...        
} 

public static void main (String[] args ) {
  Scanner input = new Scanner(System.in);
  int choice = -1;
  while (choice != 5) {
     System.out.print("1) add, 2) subtract, 3) divide, 4) multiply 5) quit");
     int choice = input.nextInt();
     // Get x, y, result
     switch (choice){ 
            case 1: 
                result = add(x, y);
                break; 
            case 2: 
                result = subtract(x, y);
                break; 
            case 3: 
                result = divide(x, y);
                break; 
            case 4: 
                result = multiply(x, y);
                break; 
            default: 
                System.out.println("Exiting program...");
                return;
           break;
      }
  }

请注意,您可能应该利用从函数(方法)传递“ return value”的功能。还要注意,方法通常是“ camel case”(例如“ addNumbers()”,而不是“ Addition()”。)。