brian Chiem
brian Chiem

Reputation: 245

Index out of bounds error

I am having trouble with my code. I can tell why I am getting an index out of bound error. This code is suppose to combine 2 byte arrays into one. According to the "list[position] = byteAdd[t];" but I cannot figure out what's wrong. These arrays are initialized at 200 byte size.

Scanner input = new Scanner(System.in); 
System.out.println("Enter a web Address");
String net = input.nextLine();
String nets [] = net.split("\\.");
byte[] length = new byte [200];
byte[] byteAdd= new byte[200];
int bytelength = byteAdd.length*2;
byte[] list = new byte [200]; 

for (int i = 0 ; i<nets.length; i++ )
{
    length[i]= (byte)(double) ( nets[i].length());  
    System.out.println(length[i]);
}

for (int i = 0 ; i<nets.length; i++ )
{
    byteAdd = nets[i].getBytes();
}

int position= 0 , max= 0;  

for (int i = 0 ; i<bytelength; i++)
{
    list[position]=length[i];
    position++;
    for (int t = 0 ; t<length[i]; t++)
    {
        list[position] = byteAdd[t];
        System.out.println(t+"   "+length[i]);
        System.out.println("Array lenght" + list.length);
        //System.out.println(t+"inner" + position);
        position++;
    }
    //System.out.println(i+"outter");
}

is this the stacktrace ?

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at test.test.main(test.java:51)

The error is on this line list[position] = byteAdd[t];

Upvotes: 1

Views: 2640

Answers (2)

NoobEditor
NoobEditor

Reputation: 15891

Your list = new byte [200]; declares list of size 200

bytelength is size 200*2 = 400

So when you say

for (int i = 0 ; i<bytelength; i++)

this means

for (int i = 0 ; i<400; i++) //whereas all array is limited to size 200 and that's throwing exception!

so, in your increment pointer, position++, this goes upto value 399 whereas, the array size is limited to 200

so list[position] goes upto list[201-400] // should be truncated at 200

Upvotes: 1

Ritikesh
Ritikesh

Reputation: 1228

position++ at two different places in the same loop will at some point cause the value of itself to be higher than the array length. Hence when trying to use it as an index to the loop, might throw An INDEXOUTOFBOUNDS exception when you're using that position value to index an out of range array index. Hence you might want to do: Either check for the position's value(if it is lesser than the array length) before using it or alter your logic. We could help if you could be clearer with what you're trying to do.

Upvotes: 0

Related Questions