Search code examples
javadata-conversionradix

Why does this for loop run into an ArrayIndexOtOfBounds error? (Java)


What i'm trying to do is have my code convert integers to base 2 and then turn those values into elements in a string array. I'm trying to avoid using Integer.toBinary(). If I could get some help that would be incredibly helpful.

public String[] streamChars(int[] colAvgs)
{
 String avgString = Arrays.toString(colAvgs);
 String convBases[] = avgString.split(",");
 int remainder;
 for (int a =0;a<colAvgs.length;a++)
 {
  remainder = colAvgs[a];
   while(remainder>0)
    {
     remainder = remainder%2;
     if ((remainder%2)==0|| (remainder%2)==1)
      {
       convbases[a] = Integer.toString(remainder);
       a++;
      }//end if
    }//end while
 }//end for
return convbases;
}//end streamChars

Thank you for your time!


Solution

  • Your remainder doesn't make it to 0 before a reaches the colAvgs value, and after that, trying to access convbases[a] crashes.

    Your while should take into account that a cannot be higher or equal than colAvgs.

    int size = colAvgs.length;
    for (int a =0;a<size;a++)
     {
      remainder = colAvgs[a];
       while(remainder>0 && a<size)
        {
         remainder = remainder%2;
         if ((remainder%2)==0|| (remainder%2)==1)
          {
           convbases[a] = Integer.toString(remainder);
           a++;
          }//end if
        }//end while
     }//end for
    if(remainder>0) //you know it finished due to a being too big.
    else //this is what you want to happen
    

    However, I think it's important to note that it's a good practice to not modify the looping variable inside a for loop, because that's part of the for's job. You should not do a++ inside the while loop. You use a for loop when you know exactly the number of iterations the loop will run. You don't have that information here. Thus, you should either change the looping condition (in this case a<size when initiating the for loop), or use a while loop instead.