I need to write a program to generate some random numbers without having two numbers fall in a certain range. Unfortunately, I need to do it at school and the only language I can use on the computers is Java (I would otherwise do it in C++). I know very little Java, and my program is giving me a stack overflow after generating 20 or so numbers. Could someone please explain why? The program is somewhat ugly, but I really need it ready in a hurry.
import java.io.*;
import java.util.*;
public class RandomNumbers {
public static int GenerateNumber(int previousNumber, int[] numberUsed) {
Random random = new Random();
int number = random.nextInt(39);
if (previousNumber >= 1 && previousNumber <= 9) {
while (number >= 1 && number <= 9)
number = random.nextInt(39) + 1;
} else if (previousNumber >= 10 && previousNumber <= 17) {
while (number >= 10 && previousNumber <= 17)
number = random.nextInt(39) + 1;
} else if (previousNumber >= 18 && previousNumber <= 32) {
while (number >= 18 && previousNumber <= 32)
number = random.nextInt(39) + 1;
} else if (previousNumber >= 33 && previousNumber <= 41) {
while (number >= 32 && number <= 41)
number = random.nextInt(39) + 1;
}
return number;
}
public static void main(String[] args) {
int[] numberUsed;
numberUsed = new int[40];
for (int i = 0; i < 40; ++i) {
numberUsed[i] = 0;
}
int previousNumber = 0;
for (int y = 0; y < 40; ++y) {
int number = 1;
while (numberUsed[ number = GenerateNumber
(previousNumber, numberUsed) ] != 0);
numberUsed[number] = 1;
previousNumber = number;
System.out.println(y);
}
}
}
EDIT: Okay, so now, for some reason, the for loop (the one with y as a counter) is not running 40 times when I include the while loop. Can someone explain why this is happening?