下面是我正在处理的一些代码,我想我应该自己做一个二进制计算器,让我的生活更轻松一些。但是,当我运行它时,我收到一条错误消息,告诉我存在 Java.lang.StringIndexOutofBoundsException
。我真的不知道如何解决它,因为据我所知,我已经正确地完成了所有事情:
private static void ten()
{
Scanner scan = new Scanner(System.in);
System.out.println("What number would you like to convert to binary?");
System.out.print("Enter the integer here: ");
int x = scan.nextInt();
String bon = Integer.toString(x , 2);
int myArrays [ ] = new int [ 7 ];
myArrays[0] = bon.charAt(0);
myArrays[1] = bon.charAt(1);
myArrays[2] = bon.charAt(2);
myArrays[3] = bon.charAt(3);
myArrays[4] = bon.charAt(4);
myArrays[5] = bon.charAt(5);
myArrays[6] = bon.charAt(6);
myArrays[7] = bon.charAt(7);
for (int i = 0; i < myArrays.length; i++)
{
System.out.print(myArrays [ i ] + " ");
int count = 0;
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
}
最佳答案
根据您输入的数字,二进制字符串的长度会有所不同。如果您输入 0 或 1,您将得到“0”或“1”。但是您的代码假定您的号码有 8 位。这意味着它只有在设置了第八位时才会起作用。
看起来您正在尝试打印由空格分隔的位,然后是新行。最好使用更直接的方法:
String b = Integer.toString(x, 2);
for (int idx = 0; idx < b.length(); ++idx) {
System.out.print(b.charAt(idx));
System.out.print(' ');
}
System.out.println();
关于java - 转换为二进制 - 获取 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35373187/