Difficulty with nested FOR loop

Asked

Viewed 352 times

1

I am creating a code to develop my studies in java and gave me an idea/ interesting challenge:

One person has 5 Megasena cards and always plays with the same cards. I made a little code where you type the numbers of the last draw and it checks to see if it matches the cards. Look:

    public static void main(String[] args) {


    int[] cartela1 = {13,25,32,47,59,60};
    int[] cartela2 = {14,26,33,48,55,60};
    int[] cartela3 = {18,63,41,25,21,36};
    int[] cartela4 = {14,26,33,48,55,60};
    int[] cartela5 = {13,25,32,47,59,60};
    int[] numSorteio = new int[6];
    int i,j;
    int count = 0;

    Scanner scan = new Scanner(System.in);

    for (i=0; i<numSorteio.length; i++) {
        System.out.println("Digite o número sorteado na posição: " +i);
        numSorteio[i] = scan.nextInt();
    }

    for (i=0; i<6; i++) {
        for (j=0; j<6; j++) {
            if (numSorteio[j] == cartela1[i]) {
                System.out.println("Seu número " + cartela1[i]+ " foi sorteado!");
                count++;
            }
        }
    }

    System.out.println("Você acertou " +count+ " números na cartela 1!");
}

As you can see my code works perfectly showing in the output the numbers I hit and the amount.

However I could only do for the cartela1, if I repeated the FOR 5 times would be perfect for 5 cartelas, however I wanted to make it shorter and elegant.

2 answers

2

I did it this way:

  1. The same loop is doing the comparison of the numbers for the first card can be used to make comparisons of all the 5 tickets as can be checked below

  2. To print the result we will change the type of the Count variable, which was an integer, for vector, so we can store the counts the hits of each card in a position distinct from the vector (ex: zero position stores the amount of hits from the first pack, position 1 stores the amount of hits of the second card and so on and so forth.)

  3. We can call a for to print the correct amount of each cartela as seen at the end of the code.

The code went like this:

public static void main(String[] args) {
    // TODO code application logic here

    int[] cartela1 = {13,25,32,47,59,60};
    int[] cartela2 = {14,26,33,48,55,60};
    int[] cartela3 = {18,63,41,25,21,36};
    int[] cartela4 = {14,26,33,48,55,60};
    int[] cartela5 = {13,25,32,47,59,60};
    int[] numSorteio = new int[6];
    int i,j;
    int[] count = new int[5];

    Scanner scan = new Scanner(System.in);

    for (i=0; i<numSorteio.length; i++) {
        System.out.println("Digite o número sorteado na posição: " +i);
        numSorteio[i] = scan.nextInt();
    }

    for (i=0; i<6; i++) {
        for (j=0; j<6; j++) {
            if (numSorteio[j] == cartela1[i]) {
                System.out.println("Seu número " + cartela1[i]+ " foi sorteado na cartela 1!");
                count[0]++;
            }

            if (numSorteio[j] == cartela2[i]) {
                System.out.println("Seu número " + cartela2[i]+ " foi sorteado na cartela 2!");
                count[1]++;
            }

            if (numSorteio[j] == cartela3[i]) {
                System.out.println("Seu número " + cartela3[i]+ " foi sorteado na cartela 3!");
                count[2]++;
            }

            if (numSorteio[j] == cartela4[i]) {
                System.out.println("Seu número " + cartela4[i]+ " foi sorteado na cartela 4!");
                count[3]++;
            }

            if (numSorteio[j] == cartela5[i]) {
                System.out.println("Seu número " + cartela5[i]+ " foi sorteado na cartela 5!");
                count[4]++;
            }
        }
    }

    for(i = 0 ; i<count.length ; i++){
    System.out.println("Você acertou " +count[i]+ " números na cartela "+ (i+1)+"!");

    }
}
}

0

Another option. If you have any questions, just ask. I used some resources that maybe you haven’t studied yet to stimulate you to search and learn more. ;)

public static void main(String args[]) {
        int[] a = {50, 30, 20, 60, 40, 10};
        int[] b = {21, 10, 38, 40, 50, 22};
        int[] c = {45, 44, 30, 25, 50, 16};
        int[] d = {55, 33, 60, 40, 49, 12};
        int[] numerosSorteados = {10,21,22,38,40,50};

        checarCartelas(numerosSorteados, a, b, c, d);
    }

    //Método tem dois parâmetros: o primeiro sempre será a lista de números sorteados
//O segundo poderá receber N cartelas (isso se chama parâmetro varargs e lhe permite passar
//1, 20, 100 cartelas, quantas quiser)
private static void checarCartelas(int[] numerosSorteados, int[]... cartelas) {
    //Ordena os números sorteados (ordenar simplifica o algoritmo, precisaremos
    //percorrer as cartelas apenas uma vez)
    Arrays.sort(numerosSorteados);

    int numeroDaCartela = 0;

    //Examinamos uma cartela por vez
    for (int[] cartela: cartelas) {

        //Ordenamos a cartela atual
        Arrays.sort(cartela);

        int quantidadeAcertosNaCartela = 0;

        System.out.println("Examinando cartela " + ++numeroDaCartela);

        //Comparamos cada número da cartela atual com cada um dos números sorteados
        for (int i = 0; i < cartela.length; i++) {
            for (int j = 0; j < cartela.length ; j++) {

                if(cartela[i] == numerosSorteados[j]) {
                    quantidadeAcertosNaCartela++;
                    System.out.println("Seu número " + cartela[i] + " foi sorteado na cartela " + numeroDaCartela);
                }
            }
        }

        if(quantidadeAcertosNaCartela > 0) {
            System.out.println("Parabéns, você teve " +
                    quantidadeAcertosNaCartela +
                    //Usamos um if ternário para que a mensagem
                    // seja gramaticalmente correta (os detalhes importam!!)
                    (quantidadeAcertosNaCartela <= 1 ? " acerto" : " acertos"));
        } else {
            System.out.println("Nenhum número acertado");
        }
    }
}
  • There is really a lot there that I don’t know yet and I don’t understand it, but I’m learning it. Your code has kept me awake the last few days. After much headbanging I discovered that there is an addiction. It only matches between a number in the "number" array and a number in one of the "A,B,C or D" arrays if it matches the numbers being in the same position in the arrays; for example: ARRAY_CARTELA: {1,19,21,37,48,54} ARRAY_SORTEIO: {1,18,19,29,44,54} The winning numbers are: 01, 19 and 54. The code says it was only 01 and 54, because it beats the position in the arrays, but 19 it ignores.

  • You are absolutely right. I have adjusted the code and now it should work smoothly. Mark the question as correct if it meets what you need.

Browser other questions tagged

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