1

So for extra credit for my math class I'm writing a program to visualize pi. Every 6 digits is converted to a hex color.

However, I'm running into an error when I try to scale the colors (since with 2 digits each for r, g, and b I can only go up to 99 and I want to go to 255). I go through a few thousand digits of pi and run this scale function on each set of 6 and then write it to a pixel in a BufferedImage, but I keep getting a StringIndexOutOfBoundsException. When I tried setting retArray[i+1] = subArray[0] I get the same error but this time at line 5. Any idea what's going on?

    private String scale(int org){
    tmp = Integer.toString(org);
    retArray = new char[6];
    for(int i=0; i<=4; i+=2){
        tmpsub = tmp.substring(i, i+2);             //line 5
        int2 = Integer.parseInt(tmpsub);
        tmpint = (((float)(int2)/99)*255);
        intie = (int)(tmpint);
        tmpsub = Integer.toHexString(intie);
        subArray = tmpsub.toCharArray();
        retArray[i] = subArray[0];
        retArray[i+1] = subArray[1];      //String Index Exception on this line
    }
    retString = "";
    for(int i=0; i<retArray.length; i++)
        retString+=retArray[i];
    return retString;
}

Thanks so much for any help with this problem. Hopefully it's something obvious that I don't see.

High Performance Mark
  • 77,191
  • 7
  • 105
  • 161
  • I guess...it doesn't really make sense though since it still runs fine but only for about 100 iterations or so instead of the full almost 10000. and it gets the error partway through...after it's done a bunch. – user1277591 Mar 19 '12 at 02:43
  • ahhh I think I'm on to something. When I only told it to go through 10 sets it didn't give me an error. And then I tried searching for the number 0 in any of the strings it handled and there were none. I think if I have something like 05 it's replacing it with 5 and making the length of the hex string 1. – user1277591 Mar 19 '12 at 02:50
  • See also [`PiRaster`](http://stackoverflow.com/a/7298492/230513). – trashgod Mar 19 '12 at 04:21

1 Answers1

1

The problem is with Integer.toHexString().

If you give it a value that is less than 0x10 (16 in decimal,) you'd get a string of length one as a result, and then subArray[1] would throw an exception.

Shay
  • 980
  • 1
  • 6
  • 9