Show attributes of an array through a menu in Java

1

In the procedure of searching for data, I search with a name to show the address, and it only shows me the first company entered, if I look for number 2 or 3 it tells me that there is none with that name. Any idea why this happens?

Data Class:

import java.util.Scanner;

import java.util.InputMismatchException;

public class Datos 
 {

int contador=0;

    static final int nDatos = 3;
    Scanner leer = new Scanner (System.in);
    char[] cEmpresa = new char[30];
    char[] cDomicilio = new char[40];
    char[] cCod_Postal = new char[30];
    char[] cLocalidad = new char[20];
    char[] cPais = new char[30];
    Datos vector[] = new Datos[nDatos];
    String empresa = new String(cEmpresa);
    String domicilio = new String(cDomicilio);
    String cod_postal = new String(cCod_Postal);
    String localidad = new String(cLocalidad);
    String pais = new String(cPais);

   public Datos(String empresa, String domicilio, String cod_postal, String localidad, String pais){
       super();
       this.empresa = empresa;
       this.domicilio = domicilio;
       this.cod_postal = cod_postal;
       this.localidad = localidad;
       this.pais = pais;
   }


    public Datos() {
    }


    public String getEmpresa() {
        return empresa;
    }

    public void setEmpresa(String empresa) {
        this.empresa = empresa;
    }

    public String getDomicilio() {
        return domicilio;
    }

    public void setDomicilio(String domicilio) {
        this.domicilio = domicilio;
    }

    public String getCod_postal() {
        return cod_postal;
    }

    public void setCod_postal(String cod_postal) {
        this.cod_postal = cod_postal;
    }

    public String getLocalidad() {
        return localidad;
    }

    public void setLocalidad(String localidad) {
        this.localidad = localidad;
    }

    public String getPais() {
        return pais;
    }

    public void setPais(String pais) {
        this.pais = pais;
    }

    void Menu() {

        Scanner sn = new Scanner(System.in);
        boolean salir = false;
        int opcion; //Guardaremos la opcion del usuario

        while (!salir) {

            System.out.println("1. Cargar Empresa");
            System.out.println("2. Listar Empresas");
            System.out.println("3. Buscar Empresa");
            System.out.println("4. Salir");

            try {

                System.out.println("Escribe una de las opciones");
                opcion = sn.nextInt();

                switch (opcion) {
                    case 1:
                        PedirDatos ();
                        break;
                    case 2:
                        MostrarDatos();
                        break;
                    case 3:
                        BuscarDatos();
                        break;
                    case 4:
                        salir = true;
                        break;
                    default:
                        System.out.println("Solo números entre 1 y 4");
                }
            } catch (InputMismatchException e) {
                System.out.println("Debes insertar un número");
                sn.next();
            }
        }

    }

    void PedirDatos (){

        int opc;

        do  {

            if (contador>=nDatos) {
                System.out.println("Maximas empresas permitidas");
                System.out.println("");
                Menu();
            }
                System.out.println("Empresa:");
                empresa = leer.nextLine();
                System.out.println("Domicilio:");
                domicilio = leer.nextLine();
                System.out.println("Codigo Postal:");
                cod_postal = leer.nextLine();
                System.out.println("Localidad:");
                localidad = leer.nextLine();
                System.out.println("Pais:");
                pais = leer.nextLine();
                vector[contador]= new Datos(empresa, domicilio, cod_postal, localidad, pais);
                contador++;
                System.out.println("Agregar otro usuario");
                opc = leer.nextInt();
                leer.nextLine();

        }while (opc==1);

    }
    void MostrarDatos() {

        for (int i = 0; i<contador; i++) {
            System.out.println("Empresa " + i +": " + vector[i].empresa);
            System.out.println("Domicilio " + i +":" + vector[i].getDomicilio());
            System.out.println("Codigo Postal " + i +":" + vector[i].getCod_postal());
            System.out.println("Localidad " + i +":" + vector[i].getLocalidad());
            System.out.println("Pais " + i +":" + vector[i].getPais());
            if (contador == 1) {
                return;

            }
        }
    }


        void BuscarDatos() {

            Scanner leer=new Scanner(System.in);
            System.out.println("Nombre a buscar:");
            String nombreAux = leer.nextLine();

                 for(int i = 0 ; i < contador;i++) {

                    if (nombreAux.equals(vector[i].getEmpresa())) {

                            System.out.println(vector[i].getDomicilio()); 
                            break;
                                }

                            else {
                                System.out.println("No hay empresa con ese nombre");
                                Menu();}                                        

                        }

                    }   
                }

Main class:

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

        Datos c = new Datos();
        c.Menu();
}

    private static void Menu() {

    }
}
    
asked by Guillermo Rubio 30.05.2018 в 13:47
source

1 answer

0
  • Your exercise can be made shorter, easier and organized using Data ArrayList to save more than one company and work with them. You can add and remove quickly, a little research on this will help you.

  • Why is your Main class practically empty? You should have     the menu here.

  • Why when you make a Data instance, all the arguments     are null ? This is not a good practice, if all will be null     then, just do not put them and to allow the instance of     the Data class, you build an empty constructor in that class.     Sure you can investigate what an empty constructor is.

  • In the Main class you have a method called Menu() that does not     nothing? Would not it be better to remove it?

  • In the constructor you have in the Data class you are not saving         the values that your variables have. When you enter the data of         the company and you do this new Datos(empresa, domicilio, .....) ,         you are making a call to the class constructor. Then inside         from the constructor you have empresa =""; which is not doing anything,         simply cleaning the variable, that is, you are not assigning         data of the company that you requested anywhere.
  • In your method MostrarDatos() you may be presented with the error java.lang.NullPointerException What would happen if you only enter 1 company and try to list companies? Here the error will appear mentioned, I show you below why. To solve this you must have a way out of for once the first company has been shown, otherwise, the error will appear and your program will fail.
  • ShowData () method incorrect to show more than 1 company

    void MostrarDatos() {
    
    // Si solo tenemos 1 empresa, la variable contador = 1
    
            for (int i = 0; i < vector.length; i++) {
    
                System.out.println("Empresa " + i + ": " + vector[i].getEmpresa());
                ..
                ...
                ....
                .....
                // La primera iteración será exitosa pero...
                // En la segunda iteración, es decir, dentro de vector[i + 1]
                // no habrá datos para mostrar y se presentará el error
            }
        }
    

    ShowData () method to show 2 companies (a quick way to do it)

    void MostrarDatos() {
    
            for (int i = 0; i < vector.length; i++) {
    
                System.out.println("Empresa " + i + ": " + vector[i].getEmpresa());
                System.out.println("Domicilio " + i + ":" + vector[i].getDomicilio());
                System.out.println("Codigo Postal " + i + ":" + vector[i].getCod_postal());
                System.out.println("Localidad " + i + ":" + vector[i].getLocalidad());
                System.out.println("Pais " + i + ":" + vector[i].getPais());
    
                // Si solo hay 1 empresa
                // Salir del for para evitar el error "java.lang.NullPointerException"
                if (contador == 1) {
                    break;
                }
            }
        }
    

    Builder arranged for your class Data:

    public Datos(String empresa, String domicilio, String cod_postal, String localidad, String pais) {
            super();
            this.empresa = empresa;
            this.domicilio = domicilio;
            this.cod_postal = cod_postal;
            this.localidad = localidad;
            this.pais = pais;
        }
    

    With this change in the constructor, the data of the companies you enter will be displayed correctly.

    SearchData () Method

    void BuscarDatos() {
    
            boolean encontrada = false;
    
            do {
                System.out.println("\nNombre de la empresa:");
                String nombre = leer.nextLine();
    
                for (int i = 0; i < vector.length; i++) {
    
                    // Si la empresa fue encontrada
                    if (vector[i].getEmpresa().equals(nombre)) {
                        System.out.println("\nEmpresa encontrada...");
                        System.out.println("Domicilio: " + vector[i].getDomicilio() + "\n");
                        encontrada = true; // Salir del do-while
                        break; // Salir del for
                    }
                }
    
                // Si la empresa no fue encontrada
                if (!encontrada) {
                    System.out.println("Empresa no encontrada!\n");
                }
    
            } while (!encontrada);
        }
    

    With this method called Find Data, if you have both companies you can search for any of them by name but there is a problem, the same one that I mentioned above about NullPointerException . If you only enter 1 company, when searching for your name you will find it correctly but, if you enter a wrong name, the error will appear. To avoid these errors you can check before entering for if vector has information or not and how much information you have, if it is 1 company or has 2.

    As you can see, I do not solve all the problem because really fixing it is something easy, you just have to think a little and that will be your job so you can develop logic.

    I hope I have helped you.

        
    answered by 30.05.2018 / 17:45
    source