我正在开发一个数学测验程序,它将询问用户是否需要加法,减法,除法或乘法测验。那么通过使用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;
}
适当的语法将是,例如:
switch (choice){
case 1:
Addition();
break;
case 2:
Subtraction();
break;
case 3:
Division();
break;
case 4:
Multi();
break;
default:
break;
}
我建议通常使用camelcase在Java中命名方法
我想你真的想要这样的东西:
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()”。