lundi 11 septembre 2017

School assignment: Generating 7 random numbers, putting them into an array, and making sure each number is unique

So, I have to make a program where I have 7 random numbers and then I have to put them into an array. Each number in the array cannot be the same as another number in the array. I wrote a program which does this, however it only works some of the time. When it does work, it works perfectly, and when it doesn't work, the program just runs forever and I have to force stop it.

I can't seem to find my mistake. Please help!

Here is my code:

package arraysex2;

import java.util.Random;
import java.util.Scanner;
public class ArraysEx2 {


    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        Random r=new Random();
        int random,count=0,count2;
        boolean isRepeat=false;
        Integer[]randoms=new Integer[7];

        while(count<=randoms.length-1){
            random=r.nextInt(30)+1;
            for(count2=0;count2<count;count2++){
                if(random==randoms[count2]){
                    isRepeat=true; 
                    break;
                }
            }
            if(!isRepeat){ 
              randoms[count]=random;
              count++; 
            }   
        }
        for(count=0;count<=randoms.length-1;count++){
            System.out.print(randoms[count]+" ");
        }
    } 
}




Aucun commentaire:

Enregistrer un commentaire