Binary conversion - getting IndexOutOfBoundsException

Below is the code I'm working on, I thought I'd make myself a binary calculator to make my life a bit easier. However, when I run it, I get an error message indicating that there is Java.lang.StringIndexOutofBoundsException. I really don’t know how to fix it, because, as far as I can tell, I did everything right:

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;
        }
    }

}
+4
source share
7 answers

. 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();
+1

, 7, 0-6, [7],

0

myArrays - 7- len, 0 7, .

0 6!

0

... int myArrays [ ] = new int [ 8 ];

0

:

1.

int myArrays [] = new int [7];

:

int myArrays [] = new int [8];

2.

You call bon.charAt()without checking that your variable bonhas enough characters.

0
source

Java.lang.StringIndexOutofBoundsException Quite a lot indicates that the length of the string is less than the index. You must consider the length. In addition, there are others in arrays beyond the boundaries that others have talked about.

0
source

Try the following:

Replace these two lines:

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

With these lines (1 only to display the initial value):

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

Source: https://habr.com/ru/post/1628579/


All Articles