mercredi 30 janvier 2019

How can I randomly choose a number from an array without duplicates? [duplicate]

This question already has an answer here:

I'm a beginner programmer and I'm trying to make a program where the user inputs 3 numbers and then 3 random numbers appear on screen and if the numbers the user entered match up with the 3 random numbers, the user wins.

Till now, it works fine but I don't want duplicate random numbers because that would cause the game to be impossible to win.

The whole thing is still works in progress but I just wanted it to work for now :)

Thanks guys!

I've tried using If statements but I don't know how to get it to work.

public static void main(String[] args) {

    int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter first number> ");
    int firstNum = Integer.parseInt(sc.nextLine());
    System.out.print("Enter second number> ");
    int secondNum = Integer.parseInt(sc.nextLine());
    System.out.print("Enter third and final number> ");
    int thirdNum = Integer.parseInt(sc.nextLine());

        System.out.println(getRandom1(numbers) + "," + getRandom2(numbers) 
                           + "," + getRandom3(numbers));


    if (firstNum == getRandom1(numbers) && secondNum == getRandom2(numbers)
        && thirdNum == getRandom3(numbers)) {
        System.out.println("Winner!!");
    } else {
        System.out.println("nope");
    }

}

public static int getRandom1(int[] array) {
    int rnd = (int) (Math.random() * array.length);
    return array[rnd];
}

public static int getRandom2(int[] array) {
    int rnd = (int) (Math.random() * array.length);
    return array[rnd];
}

public static int getRandom3(int[] array) {
    int rnd = (int) (Math.random() * array.length);
    return array[rnd];
}

}

I am expecting the output to be like 6, 5, 8. Without any duplicates.




Aucun commentaire:

Enregistrer un commentaire