View Single Post
  #2 (permalink)  
Old 08-01-2007, 10:23 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
Here's a small example: filling an array with unique numbers.
Code:
import java.util.*; public class LoopTesting { public static void main(String[] args) { Random rand = new Random(); int seed = 20; int count = 0; int[] vals = new int[10]; // Initialize elements with -1 to avoid value of zero. Arrays.fill(vals, -1); // Fill the vals array with unique numbers [0 - 19]. while(count < vals.length) { int next = rand.nextInt(seed); if(isUnique(next, vals)) vals[count++] = next; } System.out.printf("vals = %s%n", Arrays.toString(vals)); } private static boolean isUnique(int n, int[] array) { for(int j = 0; j < array.length; j++) { if(array[j] == n) return false; } return true; } }
Reply With Quote