Ceara
Ceara

Reputation: 11

How to get ArrayList shuffle to produce more than one not all the same

Hi complete novice with Java, this is my second assignment. I have written a method for a lottery code using array list, I have two issues:


public static void irishLottery() {
    Scanner input = new Scanner(System.in);
    double cost = 0;
    System.out.println("How many lines of lottery up to 10 would you like?");
    int linesam = input.nextInt();

    ArrayList<Integer> numbers = new ArrayList<Integer>();
    //define ArrayList to hold Integer objects

    for (int lottonos = 0; lottonos < 45; lottonos++) {
        numbers.add(lottonos + 1);
    }
    Collections.shuffle(numbers);

    System.out.print("Your lottery numbers are: ");

    for (int lncounter = 1; lncounter <= linesam; lncounter++) {
        for (int j = 0; j < 6; j++) {
            System.out.println(numbers.get(j) + " ");

        }
    }
}

Upvotes: 0

Views: 148

Answers (1)

JB Nizet
JB Nizet

Reputation: 691645

For the first problem: reshuffle the list each time you want to display a new line:

for (int lncounter = 1; lncounter <= linesam; lncounter++) {  
    Collections.shuffle(numbers);
    for (int j = 0; j < 6; j++) {
        System.out.println( numbers.get(j) + " ");
    }
}

For the second problem, don't use println(), but print(), since println() prints a new line:

for (int lncounter = 1; lncounter <= linesam; lncounter++) {  
    Collections.shuffle(numbers);
    for (int j = 0; j < 6; j++) {
        System.out.print(numbers.get(j) + " ");
    }
    System.out.println(); // new line before next line
}

Note that the standard idiom for looping in Java consists in starting from 0:

for (int lncounter = 0; lncounter < linesam; lncounter++) {  
    Collections.shuffle(numbers);
    for (int j = 0; j < 6; j++) {
        System.out.print(numbers.get(j) + " ");
    }
    System.out.println(); // new line before next line
}

Upvotes: 2

Related Questions