Java methods?

Asked

Viewed 226 times

-4

I’m developing this simple scheduling algorithm but the methods listar() and buscar() are not working, I choose and is simply ignored.

package strings;
import java.util.Scanner;

public class Agenda {
    static String contato[];
    private static String[] vetor;
    private static int MAX = 10;
    private static String []nome = new String[MAX];
    private static String []numero = new String[MAX];
    static Scanner entrada = new Scanner(System.in);
    static int i;
    static int cont;
    public static void main(String[] args) {
        //APP - LISTA DE NOMES
        //Criar um método para cada opção
        //Integrar esse App ao banco de dados
        //Integrar front-end

        int operacao, i, contador=0;

        while(true) {
        System.out.println(" opção 1: Adicionar contato  ");
        System.out.println(" opção 2: Listar contatos    ");
        System.out.println(" opção 3: Buscar contato     ");
        System.out.println(" opção 4: Atualizar contato  ");
        System.out.println(" opção 5: Deletar contato    ");
        System.out.println(" DIGITE ZERO PARA SAIR       ");
        operacao = entrada.nextInt();
        switch (operacao) {
        case 1:
                //Adicionar contato
                adicionar(contato);
            break;
        case 2:
                //listar contatos
                listar();
            break;
        case 3:
                //Buscar contato
                buscar();
            break;

        case 4:
                //Atualizar contato
            break;
        case 5:
                String remove;
                System.out.println("Escolha um contato a ser removido ");
                remove = entrada.next();
                remover(remove);
            break;
        case 0:
            System.out.println("Sistema Finalizado!");
            break;

            default:
                System.out.println("Informe outro número");
        }
        }//fim do laço
    } //fim do Método main.

public static void adicionar(String[] contato) {
    int cont=0;
    System.out.println("Adicionar nome: ");
    nome[i] = entrada.next();
    System.out.println("Adicionar numero: ");
    numero[i] = entrada.next();
    cont++;
}

public static void listar() {
    for(int i = 0; i < cont; i++) {
        System.out.println("Nome: "+nome[i]);
        //System.out.println("Telefone: "+numero[i]);

    }
}
public static void buscar() {
    String buscar;
    System.out.println("Informe o nome a ser buscado: ");
    buscar = entrada.nextLine();
    for(i=0; i < cont; i++) {
        if(nome[i].equalsIgnoreCase(buscar)) {
            System.out.println("Nome "+nome[i]);
            System.out.println("Numero "+numero[i]);
        }
    }
}

public static void remover(String remove){

        for(int i=0; i < nome.length; i++) {
            if(nome[i].equalsIgnoreCase(remove)) {
                nome[i] = null;
                numero[i] = null;
                break;
            }
            break;
        } 

} 
}

1 answer

4


The problem of methods listar() and buscar() is that cont will always be zero. When you declare the static variable:

static int cont;

By default it is initialized with the value zero. Then if you change the method listar() to print the value of cont:

public static void listar() {
    System.out.println("Listando " + cont + " nomes");
    ....

You will see that its value is always zero. And the problem is in the method adicionar(), because you’re creating another variable cont:

public static void adicionar(String[] contato) {
    int cont = 0;

This variable cont was created within the method, and so it exists only during the execution of the method (and in the end, it is discarded). So it is no use doing cont++ at the end of the method, as this is increasing the local variable, not the cont static.

So we can start by removing this variable from within the method, because it makes no sense: if we want a counter of all the records made, this counter cannot be a local variable to the method (which is created and destroyed at each execution).

We can also change her name to something more meaningful (cont is too generic). Example:

static int quantidadeCadastros = 0;

So I know exactly what this variable means. This makes it easier to understand the code everywhere it’s used, and also easier if you need other counters (instead of creating cont2, cont3...)

Note that I also initialized the variable with zero. Of course in this case it would not be necessary, since static variables by default are initialized with zero, but I prefer to make explicit that the program starts with no registration made.

Another detail is that you are using i in the register:

nome[i] = entrada.next();

Only this i is not being incremented (that is, all entries are being stored in the same position, since the value of i never changes).

I believe that in this case it is better to use the variable itself quantidadeCadastros for this, because it always knows the amount of registrations already made, and so we already know in which position the array should be next register.


There are still other details, such as the fact that next() do not accept spaced names, for example. In this case, it would be better to exchange for nextLine().

Speaking of which, the nextLine() in the method buscar() is not working because:

  • in making operacao = entrada.nextInt(), the newline (that would be the ENTER that we typed) at the end of the line is not consumed by Scanner
  • when entering the method buscar(), the nextLine() reads the newline of the current line (the one that had the number typed). Therefore the name to be searched is not read.

The solution, as suggested in this reply by Soen, is simply to call nextLine() right after reading the number:

operacao = entrada.nextInt();
entrada.nextLine();

That doesn’t interfere with any further calls from nextLine() (as done in the method buscar()).

Another detail is that in the method buscar() you are using the i static within the for. But that’s unnecessary, because this i only serves to traverse the array and there is no need to have a static variable for that. Then we can remove the static int i;

Then the code would look like this:

// contador de cadastros
static int quantidadeCadastros = 0;

....
// no loop while, colocar nextLine() depois de ler o número da operação:
operacao = entrada.nextInt();
entrada.nextLine();
....


// usar o contador como índice do array
// e usar nextLine() para ler o nome completo (no caso de ter espaços no nome)
public static void adicionar(String[] contato) {
    System.out.println("Adicionar nome: ");
    nome[quantidadeCadastros] = entrada.nextLine();
    System.out.println("Adicionar numero: ");
    numero[quantidadeCadastros] = entrada.nextLine();
    quantidadeCadastros++;
}

public static void listar() {
    for (int i = 0; i < quantidadeCadastros; i++) {
        System.out.println("Nome: " + nome[i]);
        // System.out.println("Telefone: "+numero[i]);
    }
}

public static void buscar() {
    String buscar;
    System.out.println("Informe o nome a ser buscado: ");
    buscar = entrada.nextLine();
    System.out.println("buscar[" + buscar + "]");
    // usar "int i", em vez do "i" estático
    for (int i = 0; i < quantidadeCadastros; i++) {
        if (nome[i].equalsIgnoreCase(buscar)) {
            System.out.println("Nome " + nome[i]);
            System.out.println("Numero " + numero[i]);
        }
    }
}

Another detail is in the option to quit the program:

case 0:
    System.out.println("Sistema Finalizado!");
    break;

This break belongs to the switch(operacao), not to the loop while(true). So option zero won’t come out of loop, and consequently, will not leave the program.

To solution is also already known: just give a name to the loop, and use the same name on break. In the example below I chose a very obvious name:

loop: while (true) { // nome bem óbvio para o loop while
    .....
    switch (operacao) {
        ....
        case 0:
            System.out.println("Sistema Finalizado!");
            break loop; // sair do loop
    }
} // fim do laço

I put the name loop, but you can put any other - just remembering to use the same name, both on while how much in the break.


There are still other details, such as this line within the method main():

int operacao, i, contador = 0;

The variables i and contador are not used, so you can remove them.

There are still other things to improve. If you do not know beforehand the amount of registrations that can be made, it is best to use java.util.List instead of arrays.

Also, if you want to group data (like name and number), it would be interesting to create a class for this:

public class Cadastro {
    private String nome;
    private String numero;
    ... (construtores, getters/setters, etc)
}

And instead of having arrays of Strings, just have a list of criminal records:

// lista de cadastros, em vez de ter dois arrays de String
List<Cadastro> cadastros = new ArrayList<>();

In the method adicionar(), just use add() to add a register:

... // ler nome e número

// adicionar o cadastro
Cadastro c = new Cadastro(nome, numero);
cadastros.add(c);

If you want to limit the number of entries, just check how many entries there are, before adding:

if (cadastros.size() < MAX) {
    // pode adicionar
}

Incidentally, size() can also be used to know how many registrations have already been made, eliminating the need to have an accountant.

Already to go through the registers (in the methods listar() and buscar()), just use a for:

for (Cadastro c: cadastros) {
    // usar c.getNome() e c.getNumero() conforme necessário
}

Browser other questions tagged

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