My assignment is to use a random number generator function to get 7 unique integers between 0 and 9, store them in an array, and display the output.
I have tried with this code below, but it fails to give me 7 unique integers. I still receive duplicate values.
Any help is appreciated, thank you.
import java.util.Scanner;
public class JavaProgramCh8Ex2 {
//Global Scanner object to read input from the user:
static Scanner keyboard = new Scanner(System.in);
//Global variable to hold the size of the array:
final static int SIZE = 7;
//Main
public static void main(String[] args) {
//Populate the array with 7 numbers:
int [] sevenNumbers = new int [SIZE];
populateSevenNumbersArray(sevenNumbers);
//Display the numbers to the user:
displaySevenNumbers(sevenNumbers);
}
//Populate the numbers array with 7 random numbers:
public static void populateSevenNumbersArray (int [] numArray){
int maxElement;
for(maxElement = (SIZE - 1); maxElement > 0; maxElement--){
for (int i = 0; i <= (maxElement - 1); i++) {
numArray[i] = getRandomNumber(0, 9);
if(numArray[i] == numArray[i + 1]){
numArray[i + 1] = getRandomNumber(0, 9);
}
}
}
}
//Display the numbers to the user:
public static void displaySevenNumbers (int [] numArray){
for (int i = 0; i < numArray.length; i++) {
System.out.print(numArray[i] + " ");
}
}
//Get random numbers to populate the 7 numbers array:
public static int getRandomNumber(int low, int high){
return (int)(Math.random() * ((high + 1) - low)) + low;
}
}