如何将这个简单的计算器程序中的 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。我如何轻松地将它更改为采用 float / double 。
最佳答案
如前所述,跳转表是指向函数的偏移量/指针的数组。与 C/C++ 不同,Java 并没有真正的函数指针 (Function Pointers in Java)
但是你可以假装,并以面向对象的方式来做。使用一种方法 (f) 定义基类 (Funky)。派生多个 child ,一个用于您的每个功能操作(+、-、*、/等),并为每个 child 创建一个对象(毕竟它只是一个接口(interface)),并将该 child 存储到一个数组中输入(时髦)。
在表中查找操作,并根据您的参数调用方法
例子:
定义一个基类,(或者一个让你更快乐的接口(interface)?)。注意,如果你扩展一个类,你可以默认使用基类方法(产生错误信息,或者抛出异常),
public class X
//or, public interface X
{
//method
Z fun(Z z1, Z z2)
{
//nothing to see here
}
}
class X1 extends X //or, implements X
{
public Z fun(Z z1, Z z2)
{
//variant1 stuff here
}
}
...
public class Xn extends X //or, implements X
{
public Z fun(Z z1, Z z2)
{
//variantn stuff here
}
}
哦,您将需要实例,并将它们加载到一个数组(跳转表)中。
某些技术对于某些语言来说是惯用的,而跳转表更多的是系统的东西而不是 Java 的东西,而不是真正的 Java 惯用语。
关于java - 在 Java 中实现跳转表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19276940/