2016-02-12 21 views
4

下面是我正在处理的一些代码,我想我会让自己成为一个二进制计算器,让我的生活变得轻松一些。但是,当我运行它时,出现错误,告诉我有一个Java.lang.StringIndexOutofBoundsException。我真的不知道如何解决它,因为据我所知,我所做的一切正确:转换为二进制 - 获取IndexOutOfBoundsException

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

您需要执行一些基本的调试:读你的异常的堆栈跟踪,因为它告诉你到底是哪一行导致了问题。然后,在该行之前添加一些'System.out.println'语句*,以便您可以看到您的String和您尝试访问的索引。 – VGR

+0

我在这里有点困惑。有些人说我应该增加一个数组,另外一些人说我应该减少一个数组。我该怎么做? – arsb48

+0

完全摆脱阵列。 – erickson

回答

0

好了,所以你有大小7数组,它只是给你0-6,但您对数组调用[7]因此通过一个

+0

我以为数组从元素“0”开始? – arsb48

+1

这是一个很好的提示,但这不是他的直接问题。 – erickson

+0

你对数组大小是正确的(应该是数组[8])。但是,这不是他得到IndexOutOfBoundsException的地方 - 它在代码行:myArrays [3] = bon.charAt(3); – pczeus

0

myArrays增加数组的大小是7元len个数组,如果你做业务从0到7,你会超出限制..从

试0到6!

0

你的数组大小需要较大... int myArrays [ ] = new int [ 8 ];

0

有在你的代码要注意两点:

int myArrays [] = new int [7]; 

应改为:

int myArrays [] = new int [8]; 

2.

您在不检查变量bon是否有足够的字符的情况下致电bon.charAt()

1

根据输入的数字,二进制字符串的长度将有所不同。如果你输入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(); 
0

Java.lang.StringIndexOutofBoundsException差不多表示字符串的长度小于索引。你应该考虑长度。还有其他人提到的其他数组越界。

0

试试这个:

替换这些2线:

String bon = Integer.toString(x , 2); 
int myArrays [ ] = new int [ 7 ]; 

有了这些线(1只显示初始值):

String byteString = Integer.toBinaryString(x & 0xFF); 
byteString = String.format("%8s", byteString).replace(' ', '0'); 
int[] myArrays = new int[8]; 
System.out.println("(" + byteString + ")");