Program to generate games and numbers of the mega sena

Asked

Viewed 563 times

3

Unfortunately I’m not managing to generate more than a set of 6 numbers. The correct one would be to generate the amount of games that the user would type and would be stored in the variable jogos.

import java.util.Random;
import java.util.Scanner;

/**
 * AtividadeMegaSena
 */

public class AtividadeMegaSena {

public static void main(String[] args) {

    Scanner teclado = new Scanner(System.in);
    System.out.println("Quantos jogos você quer fazer?");

    int jogos = teclado.nextInt();

    Random aleatorio = new Random();

    int[] numeros = new int[6];

    for (int i = 1; i <= numeros.length; i++) {
        System.out.println(aleatorio.nextInt(61));

    }

    teclado.close();

    }

}
  • What’s that 61 there?

  • it was supposed to be (60)+ 1 not to bug, is pq a mega sena the numbers that can be chosen ranging from 1 to 60

  • You can use an array whose first dimension is the number of games and the second the size of each game (6). E.g.,: int[][] jogosGerados = new int[jogos][6];. Wrap your bow with another outer loop iterating between 0 and jogos (e.g., with an index j). After generating the numbers assign each game to an input in the matrix, e.g., jogosGerados[j] = numeros;.

1 answer

5


There are at least two problems there. One of them is the described and does not have a loop to control the number of games, need to create this, it goes from 0 until just before the number typed. The other problem that this form can give repeated numbers, which is not allowed in the type of algorithm you want to do. So the best way is to generate a list of possible numbers (1-60) and have them shuffle, so it’s guaranteed that there’s no repetition, this calls Fisher-Yates scrambling algorithm.

import java.util.*;

class AtividadeMegaSena {
    public static void main(String[] args) {
        Scanner teclado = new Scanner(System.in);
        System.out.println("Quantos jogos você quer fazer?");
        int numJogos = teclado.nextInt();
        List<Integer> numeros = new ArrayList<>();
        for (int i = 1; i <= 60; i++) numeros.add(i);
        for (int i = 1; i <= numJogos; i++) {
            Collections.shuffle(numeros);
            for (int j = 0; j < 6; j++) System.out.println(numeros.get(j));
            System.out.println();
        }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks a lot for your help, buddy. It worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.