Megachu Brewster
Megachu Brewster

Reputation: 3

Random number generator continues to include 0

I'm trying to populuate an array with random numbers to be sorted and used in a binary search. All of my code seems to work fine except the generating part. The numbers need be between 1-32767 and I continue to get 0.

for(int i = 0; i < SIZE-1; i++){
   array[i] = (gen.nextInt(32767 - 1) + 1);
}

// Print out five entries
for(int i = 0; i < 5; i++){
   System.out.println(array[i]);
}

// Sort array
Arrays.sort(array);

// Print out first five sorted entries
for(int i = 0; i < 5; i++){
   System.out.println(array[i]);
}

After they're sorted and printed, the first entry is always 0. Perhaps this has to do with the array sorting, and I'm not realizing it. Any suggestions?

Upvotes: 0

Views: 299

Answers (1)

user149341
user149341

Reputation:

You're never setting the last element of the array -- use i < SIZE, not i < SIZE-1.

Upvotes: 5

Related Questions