是否可以让 char 指向数组中的对象?我试图让字符:+、-、*、/指向数组中的索引。
我很清楚下面的部分语法不正确。这只是我描述我希望实现的目标的方式。
public static void main(String[] args) {
Operations plus;
Operations minus;
Operations multiply;
Operations divide;
/**********Create jumpTable*******************/
Operations[] jumpTable = new Operations[255];
/**********Add Object to jumpTable************/
jumpTable[0] = new Addition();
jumpTable[1] = new Subtraction();
jumpTable[2] = new Multiplication();
jumpTable[3] = new Division();
/**********Point to index in table************/
plus = jumpTable[0];
minus = jumpTable[1];
multiply = jumpTable[2];
divide = jumpTable[3];
//this is what im trying to do:
//***************************************
char +;
char -;
'+' = plus
'-' = minus and etc...
//****************************************
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
System.out.printf("%f %s %f = %f%n", x, op, y, op.Compute(x, y));
}
}
最佳答案
Is it possible to have a char point to an object in an array?
假设您问:“是否可以使用 char
作为数组的索引”,那么答案是“是的,可以”。
数组的索引表达式可以具有可以提升为int
的任何类型;请参阅JLS 15.13 。并且char
类型可以提升为int
。 (您甚至不需要包含类型转换来实现它。它就可以了。)
关于java - 有一个 char 引用数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5123983/