Access values from an Object Matrix

3

I have a job where I should create a parking lot, at the very core of Java itself.

So I have my class Carros :

package estacionebemestacionamento;
import javax.swing.*;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.*;

public class Carros {
   private String Placa;
   private String Modelo;
   private String DataEntrada;
   private String HoraEntrada;
   private int HoraEntradaHora;
   private int HoraEntradaMinutos;
   private int DataEntradaDia;
   private int DataEntradaMes;
   private int DataEntradaAno;
   private String DataSaida;
   private String HoraSaida;


    public String getPlaca() { //Retorna a placa do veiculo
        return this.Placa;
    }

    public void setPlaca(String Placa) { //Armazena a Placa do Veiculo
        this.Placa = Placa;
    }

    public String getModelo() { //Retorna o Modelo
        return this.Modelo;
    }

    public void setModelo(String Modelo) { //Armazena o Modelo
        this.Modelo = Modelo;
    }

    public String getDataEntrada() { //Retorna a Data de Entrada do Veiculo
        return this.DataEntrada;
    }

    public void setDataEntrada(String DataEntrada) { //Armazena a Data de Entrada Do Veiculo
        this.DataEntrada = DataEntrada;
    }

    public String getHoraEntrada() { //Retorna a Hora de Entrada
        return this.HoraEntrada;
    }

    public void setHoraEntrada(String HoraEntrada) { //Armazena a Hora de Entrada
        this.HoraEntrada = HoraEntrada;
    }

    public String getDataSaida() {
        return this.DataSaida;
    }

    public void setDataSaida(String DataSaida) {
        this.DataSaida = DataSaida;
    }

    public String getHoraSaida() {
        return this.HoraSaida;
    }

    public void setHoraSaida(String HoraSaida) {
        this.HoraSaida = HoraSaida;
    }

    /**
     * @return the HoraEntradaHora
     */
    public int getHoraEntradaHora() {
        return HoraEntradaHora;
    }

    /**
     * @param HoraEntradaHora the HoraEntradaHora to set
     */
    public void setHoraEntradaHora(int HoraEntradaHora) {
        this.HoraEntradaHora = HoraEntradaHora;
    }

    /**
     * @return the HoraEntradaMinutos
     */
    public int getHoraEntradaMinutos() {
        return HoraEntradaMinutos;
    }

    /**
     * @param HoraEntradaMinutos the HoraEntradaMinutos to set
     */
    public void setHoraEntradaMinutos(int HoraEntradaMinutos) {
        this.HoraEntradaMinutos = HoraEntradaMinutos;
    }

    /**
     * @return the DataEntradaDia
     */
    public int getDataEntradaDia() {
        return DataEntradaDia;
    }

    /**
     * @param DataEntradaDia the DataEntradaDia to set
     */
    public void setDataEntradaDia(int DataEntradaDia) {
        this.DataEntradaDia = DataEntradaDia;
    }

    /**
     * @return the DataEntradaMes
     */
    public int getDataEntradaMes() {
        return DataEntradaMes;
    }

    /**
     * @param DataEntradaMes the DataEntradaMes to set
     */
    public void setDataEntradaMes(int DataEntradaMes) {
        this.DataEntradaMes = DataEntradaMes;
    }

    /**
     * @return the DataEntradaAno
     */
    public int getDataEntradaAno() {
        return DataEntradaAno;
    }

    /**
     * @param DataEntradaAno the DataEntradaAno to set
     */
    public void setDataEntradaAno(int DataEntradaAno) {
        this.DataEntradaAno = DataEntradaAno;
    }
}                                           

From my class carros I create a Matriz[3][3] of type Carros , so far so good.

At the time of calling my function to insert a car I do so:

public void Entrada(String Placa, String Modelo, String DataEntrada, String HoraEntrada, int HoraEntradaHora, int HoraEntradaMinutos, int DataEntradaDia, int DataEntradaMes, int DataEntradaAno){                                 
      this.Placa = Placa;
      this.Modelo = Modelo;
      this.DataEntrada = DataEntrada;
      this.HoraEntrada = HoraEntrada; 
      this.DataEntradaDia = DataEntradaDia;
      this.DataEntradaMes = DataEntradaMes;
      this.DataEntradaAno = DataEntradaAno;
      this.HoraEntradaHora = HoraEntradaHora;
      this.HoraEntradaMinutos = HoraEntradaMinutos;

      gv.setPlaca(Placa);
      gv.setModelo(Modelo);    
      gv.setDataEntrada(DataEntrada); // Armazena a data na função
      gv.setHoraEntrada(HoraEntrada);      
      gv.setDataEntradaDia(DataEntradaDia);
      gv.setDataEntradaMes(DataEntradaMes);
      gv.setDataEntradaAno(DataEntradaAno);
      gv.setHoraEntradaHora(HoraEntradaHora);
      gv.setHoraEntradaMinutos(HoraEntradaMinutos);
}

And then I allocate what is in the variable gv to a position entered by the user in my array garagem[rua][fileira] like this:

public void AlocaCarro(int Rua, int Fileira) throws Exception{
     if (garagem[Rua][Fileira] != null) {
         throw new Exception("VAGA JA OCUPADA / VAGA NÃO EXISTE.");
     }else{     
         garagem[Rua][Fileira] = gv;                    
     }                 
}

So far as I see it working, the problem is when I register more than 1 car in different positions of this matrix, and I do a search for the board to return the position of the board, it always returns me as if all the positions of the matrix was with the same card registered, it seems that it always takes the last result informed.

If I were to make an impression of all the vehicles in their places, it also returns everything the same.

public void ProcurarCarroAlocado(){          
    for (int l = 0; l < garagem.length;l++){
      for (int c = 0; c < garagem[l].length;c++){ 
          if(garagem[l][c]!=null){
            gv = garagem[l][c];
            JOptionPane.showMessageDialog(null,"Veículo com a Placa: "+gv.getPlaca()+ "localizado na Rua: "+l+"Fileira: "+c);            
          }
      }   
    }
} 

public class EstacioneBemEstacionamento{   
    public static void main(String[] args) throws ParseException {

      String Placa = "", Modelo = "";      
      String DataEntrada = null, DataSaida = null, HoraEntrada = null; 
      int HoraEntradaMinutos, HoraEntradaHora, HoraSaida, DataEntradaDia, DataEntradaMes, DataEntradaAno;   
      GaragemVagas criarVagas = new GaragemVagas();
      criarVagas.CriaVagas(); //CRIO AS VAGAS DO ESTACIONAMENTO.
      Utilitarios u = new Utilitarios();
      int Rua = 0;
      int Fileira = 0;

      //CRIA MENUS.
       System.out.println("\n\n\n");
       int opcao = 0, continuar = 1;              
        do{                        
            opcao = Integer.parseInt(JOptionPane.showInputDialog(null, "0 - SAIR \n1 - ENTRADA DE VEICULOS \n2 - PROCURAR CARRO POR PLACA \n3 - RELATORIO DIARIO \nInforme a Opção: "));                        
            switch(opcao){
              case 0:
                opcao =0;
              break;

              case 1:
                u.cls();
                Placa = JOptionPane.showInputDialog(null, "INFORME A PLACA: ");
                Modelo = JOptionPane.showInputDialog("Placa: "+Placa, "INFORME O MODELO: ");

                do {
                  DataEntradaDia = Integer.parseInt(JOptionPane.showInputDialog("Placa: "+Placa+"\nModelo: "+Modelo, "\nINFORME O DIA: "));
                }while ((DataEntradaDia < 1) || (DataEntradaDia > 31));
                do {
                  DataEntradaMes = Integer.parseInt(JOptionPane.showInputDialog("Placa: "+Placa+"\nModelo: "+Modelo+"\nDia: "+DataEntradaDia+"/", "\nINFORME O MÊS: "));                
                }while((DataEntradaMes < 1) || (DataEntradaMes > 12));
                 DataEntradaAno = 2015;


                DataEntrada = Integer.toString(DataEntradaDia) + "/" + Integer.toString(DataEntradaMes) +"/"+ Integer.toString(DataEntradaAno);

                do {
                  HoraEntradaHora = Integer.parseInt(JOptionPane.showInputDialog("Placa: "+Placa+"\nModelo: "+Modelo+"\nData de Entrada: "+DataEntrada, "\nInforme a Hora das 8 até as 18 -> (ignorando .:,)"));
                } while ((HoraEntradaHora < 8) || (HoraEntradaHora > 18));

                do {
                  HoraEntradaMinutos = Integer.parseInt(JOptionPane.showInputDialog("Placa: "+Placa+"\nModelo: "+Modelo+"\nData de Entrada: "+DataEntrada, "\nInforme os Minutos das 0 até as 59 -> (ignorando .:,)"));
                }while ((HoraEntradaMinutos < 0) || (HoraEntradaMinutos > 59));

                HoraEntrada = Integer.toString(HoraEntradaHora) + ":" + Integer.toString(HoraEntradaMinutos);                
                JOptionPane.showMessageDialog(null,"Placa: "+Placa+"\nModelo: "+Modelo+"\nData de Entrada: "+DataEntrada+"\nHora de Entrada: "+HoraEntrada);

                int op2 = Integer.parseInt(JOptionPane.showInputDialog(null, "Deseja verificar as vagas Disponíveis? \n (1)-SIM (2)-NÃO"));                
                if (op2 == 1){//IMPRIME AS VAGAS NA TELA PARA A SELEÇÃO DO USUARIO.
                  criarVagas.ImprimeVagas();
                }//FIM IMPRESSÃO

              do {                
                Rua = Integer.parseInt(JOptionPane.showInputDialog(null, "Informe a Rua onde deseja estacionar:"));
                Fileira = Integer.parseInt(JOptionPane.showInputDialog(null, "Informe a Fileira Correspondente: "));                                     
                  try {                          
                    criarVagas.Entrada(Placa, Modelo, DataEntrada, HoraEntrada, DataEntradaDia, DataEntradaMes, DataEntradaAno, HoraEntradaHora, HoraEntradaMinutos);                      
                    criarVagas.AlocaCarro(Rua, Fileira);
                    continuar = 0;
                  }catch (Exception ex){
                    JOptionPane.showMessageDialog(null,"Vaga Ja Ocupada por favor tente outra.");
                    continuar = 1;
                  }
                }while (continuar != 0);
                u.cls();//limpa saida de dados.
                break;

            case 2: //MostraPosição do Carro.
              String PlacaPesquisa = JOptionPane.showInputDialog(null,"Informe a Placa de Pesquisa: ");
              criarVagas.ProcurarCarroAlocado(PlacaPesquisa);

              break;
            case 3:
                criarVagas.ImprimeVagas();
                break;

            case 4:
                break;

            default:
                System.out.println("Opção inválida.");
            }
        } while(opcao != 0);
    }// fim main
}//fim sistema

How would my class be GaragemVagas ?

package estacionebemestacionamento;

import java.text.DateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;
import javax.swing.*;

public class GaragemVagas {
  int x,y,z;
  Carros garagem[][] = new Carros[3][3];  

  String Modelo;
  String Placa;
  String DataEntrada;
  String HoraEntrada;
  String DataSaida;
  String HoraSaida;
  int DataEntradaDia, DataEntradaMes, DataEntradaAno, HoraEntradaHora, HoraEntradaMinutos;
  int tamL;
  int tamC;
  Carros gv = new Carros();

  public void CriaVagas(){    
  //CRIA MATRIZ MULTIDIMENSIONAL DO ESTACIONAMENTO COM NENHUMA VAGA PREENCHIDA.
    for (int l = 0;l < garagem.length ;l ++){
      for (int c = 0; c < garagem[l].length; c++){
        garagem[l][c] = null;
      }
    }
  }
  public void ImprimeVagas(){
    String output = "Ruas\tFileiras\tStatus";
    String status = "";

    System.out.printf("VERIFICANDO VAGAS DISPONÍVEIS. \n");
      for(int i = 0; i < garagem.length; i++)   {    
        for(int j = 0; j < garagem[i].length; j++)    {  
           if (garagem[i][j] != null) {
             status = "Ocupada";
             output += "\n " +i+ "\t" + "" +j+ "\t("+status+")\t";
             //System.out.printf("Rua %d - Fileira %d  ( %s )\t",i,j,status);                
           }else if (garagem[i][j] == null) {
             status = "Disponível";
             output += "\n " +i+ "\t" + "" +j+ "\t("+status+")\t";
             //System.out.printf("Rua %d - Fileira %d  ( %s )\t",i,j,status);                
           }

        } 
          output += "";
         //System.out.println("");    
      }
      JTextArea outputArea = new JTextArea();
      outputArea.setText(output);
      JOptionPane.showMessageDialog(null,outputArea, "Status das Vagas",JOptionPane.INFORMATION_MESSAGE);
  } 

public void AlocaCarro(int Rua, int Fileira) throws Exception{    
  Carros novo = gv;    
  if (garagem[Rua][Fileira] != null) {
         throw new Exception("VAGA JA OCUPADA / VAGA NÃO EXISTE.");
  }else{        
      garagem[Rua][Fileira] = novo;  //guardar a referência para esta nova instância                  
  }                 
}

public void Entrada(String Placa, String Modelo, String DataEntrada, String HoraEntrada, int DataEntradaDia, int DataEntradaMes, int DataEntradaAno, int HoraEntradaHora, int HoraEntradaMinutos){                                             
      gv.setPlaca(Placa);
      gv.setModelo(Modelo);    
      gv.setDataEntrada(DataEntrada); 
      gv.setHoraEntrada(HoraEntrada);      
      gv.setDataEntradaDia(DataEntradaDia);
      gv.setDataEntradaMes(DataEntradaMes);
      gv.setDataEntradaAno(DataEntradaAno);
      gv.setHoraEntradaHora(HoraEntradaHora);
      gv.setHoraEntradaMinutos(HoraEntradaMinutos);
    }

public void ProcurarCarroAlocado(String placa){          
    String output = "Placa\tRua\tFileira";

   for (int l = 0; l < garagem.length;l++){
       for (int c = 0; c < garagem[l].length;c++){ 
           if(garagem[l][c]!=null){
              if ( garagem[l][c].getPlaca().equals(placa)){
                 output += "\n "+garagem[l][c].getPlaca()+ "\t"+l+"\t"+c;  
              }         
           }
       }
       output +="";
   }
   JTextArea outputArea = new JTextArea();
   outputArea.setText(output);
   JOptionPane.showMessageDialog(null, outputArea, "Carro Localizado",JOptionPane.INFORMATION_MESSAGE);
} 

}

Update : Bruno, I can not instantiate the way you told me.

    
asked by anonymous 27.05.2015 / 20:32

1 answer

2

The problem then lies in the AlocaCarro(...) function. You should make a copy of the object and save it in your matrix. You are currently creating a single object, which you will change during the execution of your program and to which all the positions of your matrix point (same memory address).

One solution is to create a copy constructor that lets you get what you want. - You have other ways to copy objects in Java, but for this example and since this is an introduction to Java, I would recommend this option.

In your Cars class you define the constructor as follows.

public Carros(Carros outro) {

  this.Placa = outro.placa;
  this.Modelo = outro.Modelo;
  this.DataEntrada = outro.DataEntrada
  (...fazer o mesmo para os restantes atributos...)
}

Then in your method, you will

public void AlocaCarro(int Rua, int Fileira) throws Exception{
  if (garagem[Rua][Fileira] != null) {
         throw new Exception("VAGA JA OCUPADA / VAGA NÃO EXISTE.");
  }else{     
      Carros novo(gv);  //Aqui crias uma nova instância do objecto
      garagem[Rua][Fileira] = novo;  //guardar a referência para esta nova instância                  
  }                 
}

The Carros novo(gv); line creates a new object that is a copy of the gv instance.

To search for the car per card, you can do:

public void ProcurarCarroAlocado(String placa){          
   for (int l = 0; l < garagem.length;l++){
       for (int c = 0; c < garagem[l].length;c++){ 
           if(garagem[l][c]!=null){
              if ( garagem[l][c].GetPlaca().equals(placa)
                 JOptionPane.showMessageDialog(null,"Veículo com a Placa: "+ placa+ "localizado na Rua: "+l+"Fileira: "+c);  
              }         
           }
       }   
   }
}
    
27.05.2015 / 20:44