我正在处理这个程序,它使用二进制字符串并将其转换为十进制,使用
this guide将二进制转换为十进制.当我通过我的头上的for循环,我得到正确的输出将是什么.然而,当我运行我的程序,我得到这个奇怪的输出:
@H_301_2@1
3
7
15
31
63
127
实际输出应如下所示:
@H_301_2@1
2
5
11
22
44
89
我无法想象这是为了我的生活.为什么我的程序这样做?以下是当前的源代码:
@H_301_2@public class BinaryToDecimal
{
public static void main(String[] args)
{
String binary = "1011001";
int toMultiplyBy;
int decimalValue = 0;
for (int i = 1; i <= binary.length(); i++)
{
int whatNumber = binary.indexOf(i);
if (whatNumber == 0)
{
toMultiplyBy = 0;
}
else
{
toMultiplyBy = 1;
}
decimalValue = ((decimalValue * 2) + toMultiplyBy);
System.out.println(decimalValue);
}
}
}
字符串是0,所以你应该循环通过String从0到< String的长度,但是indexOf(...)不是你想要使用的,因为这将搜索String中的小int的位置,这是没有意义的.你不在乎2的字符等同于字符串中的位置,或者即使它在String中. 而是要使用charAt(…)或subString(…),然后解析为int.我会用
@H_301_2@for (int i = 0; i < binary.length(); i++) {
int whatNumber = charAt(i) - '0'; // converts a numeric char into it's int
//...
要看看这是做什么,创建并运行:
@H_301_2@public class CheckChars {
public static void main(String[] args) {
String foo = "0123456789";
for (int i = 0; i < foo.length(); i++) {
char myChar = foo.charAt(i);
int actualIntHeld = (int) myChar;
int numberIWant = actualIntHeld - '0';
System.out.printf("'%s' - '0' is the same as %d - %d = %d%n",myChar,actualIntHeld,(int)'0',numberIWant);
}
}
}
哪个返回:
@H_301_2@'0' - '0' is the same as 48 - 48 = 0
'1' - '0' is the same as 49 - 48 = 1
'2' - '0' is the same as 50 - 48 = 2
'3' - '0' is the same as 51 - 48 = 3
'4' - '0' is the same as 52 - 48 = 4
'5' - '0' is the same as 53 - 48 = 5
'6' - '0' is the same as 54 - 48 = 6
'7' - '0' is the same as 55 - 48 = 7
'8' - '0' is the same as 56 - 48 = 8
'9' - '0' is the same as 57 - 48 = 9
表示字符的数字基于给予每个符号数字表示的旧ASCII表.欲了解更多信息,请点击这里:ASCII Table