Hash Test Quick question.

This is just a simple test of a hash key algorithm. I belive its pretty self explanatory and very short so I will spare myself and you guys the explanation.

publicclass test2

{

publicstaticint H(char symbol[],int NUM_BINS)

{

int total = 0, n = 0;

while(symbol[n]!= 0)

total += (int)symbol[n++];

return total % NUM_BINS;

}

publicstaticvoid main (String[] args){

int idNum;

char[] array =newchar[3];

char B ='B';

char C ='C';

char I ='I';

array[0] = B;

array[1] = C;

array[2] = I;

System.out.println("Array0: " + array[0]);

System.out.println("Array1: " + array[1]);

System.out.println("Array2: " + array[2]);

idNum = (int)array[0];

System.out.println("idNum array[0] is " + idNum);

idNum = (int)array[1];

System.out.println("idNum array[1] is: " + idNum);

idNum = (int)array[2];

System.out.println("idNum array[2] is: " + idNum);

System.out.println("Total or key is: " + H(array, 3));

}

Here is my output. The problem is the error message at the bottom. Why is my array out of bonds? the NUM_BINS is set to 3 and I have 3 indexes. Im confused. Can someone please give me some clarity.

Array0: B

Array1: C

Array2: I

idNum array[0] is 66

idNum array[1] is: 67

idNum array[2] is: 73

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

at test2.H(test2.java:6)

at test2.main(test2.java:44)

[2745 byte] By [venturea] at [2007-11-26 20:50:59]
# 1

while(symbol[n]!= 0)

Bet you come from C programming ;-)

Your array has no 0's, so the condition is never fulfilled and n goes from 0 to 3, but the maximum valid value for n is 2.

Review again your assignments on arrays, Strings and remember Java is not C++ ;-)

benubacha at 2007-7-10 2:15:53 > top of Java-index,Java Essentials,Java Programming...