user1277591
user1277591

Reputation: 23

Scaling RGB values in Pi

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.

Upvotes: 1

Views: 151

Answers (1)

Shay
Shay

Reputation: 1000

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.

Upvotes: 1

Related Questions