vendredi 14 janvier 2022

An array that outputs number 1-5 in random, 1-5 must be output only 2 times without repeating

The code does output 1 - 5 but is there a way to make each number print only twice. (from 1-5 only) Sample Output,

It does change and is random but outputs more than twice

public class Main {

public static void main(String[] args) {
    
int num;    

int[] random = new int[5]; //this code generates numbers 1–5 

int[] array = new int[11]; //array size

for(int x = 0; x < random.length; x++)

random[x] = x; //store the index as a value

for(int x = 0; x < random.length; x++) {

num = (int)(Math.random()*5);

while(random[num] == -1)

num = (int)(Math.random()*5); 

if(random[num] != -1)

array[x] = random[num]; 

random[num] = -1; 

}

for(int x = 0; x < array.length; x++)

array[x] = array[x] + 1;

for(int x = 1; x < array.length; x++)


System.out.println("A["+x+"]: "+ array[x]);

}

}



Aucun commentaire:

Enregistrer un commentaire