What makes the for and what makes the brackets in an array?

Asked

Viewed 754 times

5

I asked for help on some forums in an old game programmed in java, I understood the logic, but did not know how to apply it (which commands to use, and how to use), and I saw the use of Arrays. After seeing a complete code, I understood everything except for one part, that part here:

public boolean vitoria (int x){
        for (int i = 0; i < mat.length; i++){
            if(mat[i][0] == x && mat [i][1] == x && mat [i][2] == x){
                return true;
            }
            if(mat[0][i] == x && mat [1][i] == x && mat [2][i] == x){
                return true;
            }
        }
        if(mat[0][0] == x && mat [1][1] == x && mat [2][2] == x){
            return true;
        }
        if(mat[0][2] == x && mat[1][1] == x && mat [2][0] == x){
            return true;
        }
        return false;
    }

My question is, what does it mean (int = 0;i <mat.lenght; i++), and what each line means, for example

if(mat[i][0] == x && mat [i][1] == x && mat [i][2] == x){
                    return true;
                }

What do the brackets mean? and what are they doing (what function)? Remembering that in this game of old, the mat is the variable int that marks the position that each player played. Here is the complete code if necessary:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;

public class Jogo extends JFrame {
    private static final long serialVersionUID = 1L;
    private JButton b1,b2,b3,b4,b5,b6,b7,b8,b9;
    int qtde;//verifica quantidade de jogadas da partida
    int jogador;// verifica o jogador da vez, sendo 1 = X e 2 = 0
    int mat[][] = new int [3][3];//marca a posição que cada jogador jogou
    JButton b[] = new JButton[9];//mapeia os botões
    String ganhador;//armazena nome do vencedor
    String jogador1;//armazena nome do jogador 1
    String jogador2;// armazena nome do jogador 2

    public Jogo() {
        setTitle("Jogo da Velha");
        setBounds(190,100,300,400);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        getContentPane().setBackground(new Color(197,197,197));
        setLayout(null);

        JMenuBar mBar = new JMenuBar();
        JMenu opcoes = new JMenu("Opções");
        JMenuItem nJogo = new JMenuItem("Novo Jogo");

        JMenuItem sair = new JMenuItem("Sair");

        mBar.add(opcoes);
        mBar.add(sair);
        opcoes.add(nJogo);

        setJMenuBar(mBar);

        b1 = new JButton();
        b1.setBounds(25,50,60,70);
        this.add(b1);

        b2 = new JButton();
        b2.setBounds(115,50,60,70);
        this.add(b2);

        b3 = new JButton();
        b3.setBounds(205,50,60,70);
        this.add(b3);

        b4 = new JButton();
        b4.setBounds(25,140,60,70);
        this.add(b4);

        b5 = new JButton();
        b5.setBounds(115,140,60,70);
        this.add(b5);

        b6 = new JButton();
        b6.setBounds(205,140,60,70);
        this.add(b6);

        b7 = new JButton();
        b7.setBounds(25,230,60,70);
        this.add(b7);

        b8 = new JButton();
        b8.setBounds(115,230,60,70);
        this.add(b8);

        b9 = new JButton();
        b9.setBounds(205,230,60,70);
        this.add(b9);

        qtde = 1;
        jogador = 1;

        b[0] = b1;
        b[1] = b2;
        b[2] = b3;
        b[3] = b4;
        b[4] = b5;
        b[5] = b6;
        b[6] = b7;
        b[7] = b8;
        b[8] = b9;

        b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                jogada(b1,0,0);
            }
        });
        b2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                jogada(b2,0,1);
            }
        });
        b3.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                jogada(b3,0,2);
            }
        });
        b4.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                jogada(b4,1,0);
            }
        });
        b5.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                jogada(b5,1,1);
            }
        });
        b6.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                jogada(b6,1,2);
            }
        });
        b7.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                jogada(b7,2,0);
            }
        });
        b8.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                jogada(b8,2,1);
            }
        });
        b9.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                jogada(b9,2,2);
            }
        });
        nJogo.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                for(int i = 0; i < 9; i++){
                        b[i].setEnabled(true);
                        b[i].setText("");
                    }
                    for(int x = 0; x < 3; x++){
                        for(int y = 0; y <3; y++){
                            mat[x][y] = 0;
                        }
                    }
                    jogador = 1;
                    jogador1="";
                    jogador2="";
                    ganhador="";
                }

        });

    }
    public static void main (String [] args){
        new Jogo().setVisible(true);
    }
    public void jogada (JButton b, int x, int y){
        b.setEnabled(false);
        if(jogador == 1){
            mat[x][y] = 1;
            b.setText("X");
            jogador = 2;
            ganhador = jogador1;
            checarjogada(1);
        } else {
            if(jogador == 2){
                mat[x][y] = 2;
                b.setText("O");
                jogador = 1;
                ganhador = jogador2;
                checarjogada(2);
            }
            qtde++;
        }
    }
    public void checarjogada(int x){
        if(vitoria (x) == true){
            JOptionPane.showMessageDialog(null,"Jogador:"+ganhador+"Venceu!","Vitória!",1);
            fimdojogo();
        }
    }
    public boolean vitoria (int x){
        for (int i = 0; i < mat.length; i++){
            if(mat[i][0] == x && mat [i][1] == x && mat [i][2] == x){
                return true;
            }
            if(mat[0][i] == x && mat [1][i] == x && mat [2][i] == x){
                return true;
            }
        }
        if(mat[0][0] == x && mat [1][1] == x && mat [2][2] == x){
            return true;
        }
        if(mat[0][2] == x && mat[1][1] == x && mat [2][0] == x){
            return true;
        }
        return false;
    }
    public void fimdojogo(){
        for(int i = 0; i < 9; i++){
            b[i].setEnabled(false);
        }
    }
}
  • I had to publish my answer with missing data because it was bug here on the page, wait that I edit the answer with the correct data.

  • I am waiting, but do not worry, because it has helped me to understand almost completely ! I thank you already for the help !

  • ready finalized the answer, I hope to have helped to understand your doubt, if my answer served to remedy your doubt do not forget to give a positive vote and mark it as accepted response from below the vote.

  • Problem-free !

  • what are square brackets?

  • 1

    Hello @Jorgeb., the "brackets" said by me would be the arrays ! That [] are brackets!

Show 1 more comment

1 answer

10


You know what it means to be?

For is a structure of repetition, great to iterate for arrays and listas.

for (int i = 0; i <mat.lenght; i++)

This line above means:

For (for) a variable i of the kind inteiro (int) with equal initial value 0, repeat any code inside the for (That is, the block that is between the keys {} after the for. Repeat until when? Repeat until i be smaller than the size of the two-dimensional array mat; During each repetition increment i in another 1.

As you can see in your for we have three statements separated by ;. Behold:

for ( int i = 0; i < mat.length; i++ ) {
    O que está dentro dessas chaves será repetido.
}

Could see the ; in the for statement?

So the first part means this:

  1. For (for) a variable i of the kind inteiro (int) with equal initial value 0
  2. Repeat all code inside the block for (That is, the block that is between the keys {} after the for.
  3. Repeat until when? Repeat until i be smaller than the size of the two-dimensional array mat;
  4. During each repetition increment i in another 1.

Did you understand? I tried not to complicate as much as possible, I hope I helped.

As for the use of array brackets, whether one-dimensional or two-dimensional, think as follows:

int[] mat = new int [3];

The mat array has a size of 3 and, as we have a square bracket in its statement, it is a one-dimensional and integer array. Imagine mat as three empty cups. You have the cup 0, 1, 2 (Always starting from 0, but still being three cups). If you want to add any number and whatever the cup, you have to say in which cup you want to add the number like this:

mat[0] = 20; // Isso significa que o primeiro copo, representado pela POSIÇÃO 0, armazenará o elemento (número) 20.

And for the second glass?

mat[1] = 20; // Isso significa que o segundo copo, representado pela POSIÇÃO 1, armazenará o elemento (número) 20.

And so on and so forth.

Now let’s go to the BIDIMENSIONAL array.

int mat[][] = new int [3][3];//marca a posição que cada jogador jogou

Since we have two square brackets it means that the array is two-dimensional. [3] We have an array that can store 3 elements. But each element of this actually contains another array that there yes can store 3 elements, so [3][3].

[Posição 0 / Elemento 1], [Posição 1 / Elemento 2], [Posição 0 / Elemento 3]

But instead of being able to store an element within each position, you have an array within each position that can store three elements. Within Position 0, you can store Element 1, Element 2, Element 3 like this:

mat[0][0] = 20; Na primeira posição do array que está dentro da posição 0.
mat[0][1] = 30; Na segunda posição do array que está dentro da posição 0.
mat[0][2] = 30; Na terceira posição do array que está dentro da posição 0.

We finished the first array that was inside the 0 position. We added only 3 elements in this array because... Remember? [3][3] (This second 3).

  • Thank you very much friend, do not know how it helped, hope to help one day too !

  • @Gabrielozzy nothing. One hand washes the other. And the more we help, the more we learn.

Browser other questions tagged

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