我是 Java 的新手,所以如果这个问题的答案看起来很明显,我很抱歉......
我在我的类中写了一个方法如下:
private static final String[] rCode = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
private int getCharValue(String code)
{
// loop through the codes to find a
// matching code, if found exit loop (via return).
for (int position = 0; position < rCode.length; position++)
{
if (rCode[position] == code)
return rVal[position];
} // for
// otherwise return 0
return 0;
} // getCharValue
在同一个类的另一个方法中,我循环遍历字符串的字符,如下所示:
String number = "MMMCDXXXIV";
for (int pos = 0; pos < number.length(); pos++)
{
System.out.println(number.substring(pos, pos + 1) + " " + getCharValue(number.substring(pos, pos + 1)));
} // for
我的问题是,虽然我的 getCharValue() 方法在我硬编码一个值时工作正常,例如getCharValue("X")
当我调用它时它不起作用 getCharValue(number.substring(pos, pos + 1))
(即使我知道 number.substring(pos, pos + 1)
正在返回应该返回值的单个字符。
谁能看出我明显的错误?
非常感谢...
最佳答案
if (rCode[position] == code)
这在 Java 中不符合您的要求。它不是比较组成字符串的字符是否相同,而是比较两个 String 对象是否实际上是同一个对象。所以当你比较两个编译时文字时它会起作用,因为编译器足够聪明,可以将它们指向同一个内部对象。但是,当您在运行时生成新的字符串时,它将失败。
你想做的事:
if (rCode[position].equals(code))
关于java - 将字符串解析为 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4330389/