Accessing values from an object array

Asked

Viewed 309 times

3

I have a job where I should create a parking, in the basic Java same.

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;
    }
}                                           

Of my class carros I create a Matriz[3][3] of the kind 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’s in the variable gv in a user-informed position in my matrix garagem[rua][fileira] thus:

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;                    
     }                 
}

Until then to my view this working, the problem is when I register more than 1 car in different positions of this matrix, and I do a search by plate to return me the position of the plate, it always returns to me as if all the positions of the matrix were with the same registered plate, it seems that it always takes the last reported result.

If I were to make an impression of all the vehicles in their places, it returns also all 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 look 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);
} 

}

Updating: Bruno, I’m not succeeding in instantiating the way you told me.

  • I temporarily removed my answer for now I was in doubt. I do not think I understood the question correctly. Can you put in some more of your code? The part where you declare the instance variable 'Gv' and where you are calling the Input() and Alocacarro functions?

  • In the Cars class you have to declare the copy builder. Then in the Alocacarro() method you should create a copy of the Gv object as follows: "New cars Car (Gv);" and not "New cars = Gv";

  • and how I urge the Cars Gv = new Cars(); ? he asks for a parameter for the Cars(); which I put?

  • You created the "Public Cars(Cars o)" method in your Cars class?

  • Yes I created public Cars(Other car) in the Cars class, as you told me, now in the Garagemvague class as I urge the Cars Gv = new Cars(); ?

  • Also create another builder with the following signature: "Public Cars() {}.

  • I need to put the attributes in it too or not?

  • Not in your case, or you’ll have to change the way you’re instantiating the object. To be able to run "Cars Gv = new Cars()" defines the constructor without parameters. Only "public Cars() { }.

Show 3 more comments

1 answer

3


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

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

In your Cars class 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 Alocacarro you do

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 line Carros novo(gv); creates a new object which is a copy of the instance gv.

To search the car by license plate, 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);  
              }         
           }
       }   
   }
}

Browser other questions tagged

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