简体   繁体   中英

How do I store random and unique numbers in an array in Java?

I am creating a tournament generator where there are 8 teams that the user inputs. I need to do a quarter-final where there are 4 matches between random teams. This is my code so far:

import java.util.Scanner;
public class A4Q1 {

public static void main(String[] args) {
    // TODO Auto-generated method stub

System.out.println("-----------------------------------------------------");
System.out.println("   Welcome to Tournament Outcome Predictor Program");
System.out.println("-----------------------------------------------------");


Scanner sc = new Scanner(System.in);


System.out.print("\nPlease enter a name for the football tournament: ");
String tName = sc.nextLine(); //name of tournament

int nbTeams = 8;
String[] footballTeams = new String [nbTeams];

System.out.println("\nPlease enter 8 participating teams: ");

    for (int i = 0; i<nbTeams; i++) {

        footballTeams[i] = sc.nextLine(); //storing 8 teams in array

    }

My problem is that I do not know how to generate 8 random unique numbers. I was thinking of storing these number 0 to 7 in a new array but I am out of ideas!

Here is a very simple method that generates a random arrays of Integer containing each element between 0 and length (exclusive).

import java.util.*;

Integer[] randomArray(int length) {
    Random random = new Random();
    List<Integer> list = new LinkedList<>();
    for (int k = 0; k < length; k++)
        list.add(k);

    Collections.shuffle(list);
    return list.toArray(new Integer[] {});
}

Calling it leads to a different output each time:

System.out.println(Arrays.toString(randomArray(8)));

For example, it could print: [2, 4, 0, 5, 3, 6, 1, 7] .

The idea is very simple, we generate an list containing all elements that interest you, and then, use the built-in Collections.shuffle from the standard library.

Use Math.random function like this;

(int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);

where lowerbound is inclusive and upperbound exclusive.

to generate random values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM