如何将一个字符串中的一个字符与另一个字符串进行比较

我是Java的新手,为了实践起见,我试图创建一个十六进制到十进制的数字转换器,因为我已经成功地制作了一个二进制到十进制的转换器。

我遇到的问题基本上是将一个字符串中的给定字符与另一个字符串进行比较。这就是我定义要比较的当前字符的方式:

String current = String.valueOf(hex.charAt(i));

这是我尝试比较角色的方法:

else if (current == "b") 

dec += 10 * (int)Math.pow(16, power);

当我尝试通过仅输入数字(例如12)来运行代码时,它可以工作,但是当我尝试使用“ b”时,会出现一个奇怪的错误。这是运行程序的全部结果:

run:

Hello! Please enter a hexadecimal number.

2b

For input string: "b" // this is the weird error I don't understand

BUILD SUCCESSFUL (total time: 1 second)

这是仅通过数字转换即可成功运行程序的示例:

run:

Hello! Please enter a hexadecimal number.

22

22 in decimal: 34 // works fine

BUILD SUCCESSFUL (total time: 3 seconds)

任何帮助,将不胜感激,谢谢。

我认为如果将整个方法放在这里会很有用。

我不知道我应该接受谁的答案,因为它们是如此的好和有用。如此矛盾。

for (int i = hex.length() - 1; i >= 0; i--) {

String lowercaseHex = hex.toLowerCase();

char currentChar = lowercaseHex.charAt(i);

// if numbers, multiply them by 16^current power

if (currentChar == '0' ||

currentChar == '1' ||

currentChar == '2' ||

currentChar == '3' ||

currentChar == '4' ||

currentChar == '5' ||

currentChar == '6' ||

currentChar == '7' ||

currentChar == '8' ||

currentChar == '9')

// turn each number into a string then an integer, then multiply it by

// 16 to the current power.

dec += Integer.valueOf(String.valueOf((currentChar))) * (int)Math.pow(16, power);

// check for letters and multiply their values by 16^current power

else if (currentChar == 'a')

dec += 10 * (int)Math.pow(16, power);

else if (currentChar == 'b')

dec += 11 * (int)Math.pow(16, power);

else if (currentChar == 'c')

dec += 12 * (int)Math.pow(16, power);

else if (currentChar == 'd')

dec += 13 * (int)Math.pow(16, power);

else if (currentChar == 'e')

dec += 14 * (int)Math.pow(16, power);

else if (currentChar == 'f')

dec += 15 * (int)Math.pow(16, power);

else

return 0;

power++; // increment the power

}

return dec; // return decimal form

}

回答:

尝试将char初始化char为由返回的值charAt()

char current = hex.charAt(i);

然后在您的条件中使用文字char:

else if (current == 'b')

由于char是原始类型,因此可以使用==运算符进行比较。在前面的代码中,您正在比较Stringusing ==,因为a String是a,所以Object代码将检查它们是否相同,Object而不是它们是否具有与String.equals()方法相同的值。

以上是 如何将一个字符串中的一个字符与另一个字符串进行比较 的全部内容, 来源链接: utcz.com/qa/404012.html

回到顶部