我编写了一个将二进制数转换为十进制数的程序。
当我使用一些二进制数运行程序时,程序给出十进制数,但带有错误消息。
我的代码:
public class ohad {
public static void main(String[] args) {
String bin = "10011";
int length = bin.length();
int j = 0;
int sum = 0;
if (length != 0) {
for (int i=0; i < bin.length(); i++){
if (bin.charAt(i) == '0' || bin.charAt(i) == '1'){
for (int t = (length - 1); t >= 0; t--){
String s = bin.charAt(j) + "";
sum = (int)(sum + (Integer.valueOf(s)) * (Math.pow(2, t)));
j++;
}
System.out.println(sum);
}
else {
System.out.println("illegal input.");
}
}
} else {
System.out.println("illegal input.");
}
}
}
错误信息:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:646)
at ohad.main(ohad.java:15)
我认为这与我的 j 索引有关。我该怎么办?
最佳答案
我应该做什么?
我会使用Integer.parseInt(String,int)
喜欢
String bin = "10011";
System.out.println(Integer.parseInt(bin, 2));
输出为
19
关于java - 二进制转十进制,错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26874254/