JAVA POO - How to call a function from a Class

1

Then I have the following problem, I created a 30x60 matrix in which I will generate a number in a random position, so far so good. But when I get the function that generates the number and put it in the class, I'm having trouble calling it.

My code looks like this: I've omitted the matrix padding code to get smaller

int [][] matrix = new int[30][60];
Caminhao caminhoes = new Caminhao();
Carro carros = new Carro();
Moto motos = new Moto();



//Utilizando as funções com objetos

carros.gerarCarro();
motos.gerarMoto();
caminhoes.gerarCaminhao();


//Código para printar a matriz após cada veiculo adicionado

    for(int x = 0; x < matrix.length; x++)
{
    for (int i = 0; i < matrix[x].length; i++) 
    {
        System.out.print(matrix[x][i]);
    }
    System.out.println();
}

And the code in the class that is in the function looks like this:

/Método para gerar um Carro em um lugar aleatório da matriz
public void gerarCarro(){
          Random r= new Random();
          int [][] matrix = new int[30][60];
          int a =r.nextInt(29);
    int b =r.nextInt(59);
          if(matrix[a][b] == 0 && matrix[a][b] != 2 && matrix[a][b]!=1 && matrix[a][b]!=4 && matrix[a][b]!=5){
            matrix[a][b]=3;

    }

    }
}

What's wrong?

    
asked by anonymous 16.04.2018 / 00:40

1 answer

0

When you do int [][] matrix = new int[30][60]; within method gerarCarro you are creating a new array and not using it that you already had in main :

public void gerarCarro(){
    Random r= new Random();
    int [][] matrix = new int[30][60]; // <-- aqui

For this reason the following change:

matrix[a][b]=3;

Nothing affects the array you already had in main . To do what you want you have some alternatives. The most direct and common is to pass this array as a parameter to the method.

To do this, start by changing the method to work with the received matrix:

public void gerarCarro(int[][] matrix){
// -------------------------------^ matriz recebida aqui
    Random r= new Random();
    //int [][] matrix = new int[30][60]; //já não cria
    int a =r.nextInt(29);
    int b =r.nextInt(59);
    if(matrix[a][b] == 0){
        matrix[a][b]=3;
    }
}

At this point you may be thinking: And what happened to the rest of the conditions you had in if ???

Well, they did not make sense because if matrix[a][b] is 0 then it will be guaranteed otherwise than 1, 2, 4 and 5 making it redundant.

No main changes gerarCarro to send matrix .

//Utilizando as funções com objetos

carros.gerarCarro(matrix);

And to be all right, you will have to apply the same principle to the other methods that you generate, assuming you had the same logic in them.

I would still have other things to improve, such as not creating the object Random every time I enter the method, but this is already a step towards the future.

    
16.04.2018 / 01:18