如何将这个简单的计算器程序中的 switch/case 语句转换为跳转表。
import java.lang.*;
import java.util.*;
public class Calculator
{
private int solution;
private static int x, y, ops;
private char operators;
public Calculator()
{
solution = 0;
}
public int addition(int x, int y)
{
return x + y;
}
public int subtraction(int x, int y)
{
return x - y;
}
public int multiplication(int x, int y)
{
return x * y;
}
public int division(int x, int y)
{
solution = x / y;
return solution;
}
public void calc(int ops){
Scanner operands = new Scanner(System.in);
System.out.println("operand 1: ");
x = operands.nextInt();
System.out.println("operand 2: ");
y = operands.nextInt();
System.out.println("Solution: ");
switch(ops)
{
case(1):
System.out.println(addition(x, y));
break;
case(2):
System.out.println(subtraction(x, y));
break;
case(3):
System.out.println(multiplication(x, y));
break;
case(4):
System.out.println(division(x, y));
break;
}
}
public static void main (String[] args)
{
System.out.println("What operation? ('+', '-', '*', '/')");
System.out.println(" Enter 1 for Addition");
System.out.println(" Enter 2 for Subtraction");
System.out.println(" Enter 3 for Multiplication");
System.out.println(" Enter 4 for Division");
Scanner operation = new Scanner(System.in);
ops = operation.nextInt();
Calculator calc = new Calculator();
calc.calc(ops);
}
}
老实说,我不知道跳转表到底是什么(在网上找不到任何解释),所以我不知道它与 switch/case 语句有何不同。
旁注:这段代码只处理整数,所以如果你除以 5/3,它会给你 1。我怎样才能轻松地将它更改为浮点数/双精度数。