Loop with options

Asked

Viewed 1,026 times

3

How do I create a loop with options in Java? For example: "type 1 to save and 2 to delete". And when doing the commands for each option, go back to : "type 1 to save and 2 to delete".

import java.io.*;

public class CadastroPessoa{

public static void main(String[] args) throws IOException{
//burocracia para leitura de teclado
InputStream entradaSistema = System.in;
InputStreamReader leitor = new InputStreamReader(entradaSistema);
BufferedReader leitorEntrada = new BufferedReader(leitor);
String entradaTeclado;

//instanciando objetos do sistema
ControlePessoa umControle = new ControlePessoa();


System.out.println("Digite 1 para adicionar pessoa. Digite 2 para remover pessoa. Digite 3 para pesquisar uma pessoa. Digite 4 para sair.");
entradaTeclado = leitorEntrada.readLine();
String Opcao = entradaTeclado;

    String opcao1 = "1";
    String opcao2 = "2";
    String opcao3 = "3";
String opcao4 = "4"; 

while (!Opcao.equals(opcao4)){

    if (Opcao.equals(opcao1)){

        //interagindo com usuário
        System.out.println("Digite o nome da Pessoa:");
        entradaTeclado = leitorEntrada.readLine();
        String umNome = entradaTeclado;

        System.out.println("Digite o telefone da Pessoa:");
        entradaTeclado = leitorEntrada.readLine();
        String umTelefone = entradaTeclado;


        //adicionando uma pessoa na lista de pessoas do sistema
        Pessoa umaPessoa = new Pessoa(umNome, umTelefone);
        String mensagem = umControle.adicionar(umaPessoa);
        System.out.println(mensagem);
        }

    if (Opcao.equals(opcao2)){

        System.out.println("Digite o nome da pessoa que você quer remover:");
        entradaTeclado = leitorEntrada.readLine();
        String umNome = entradaTeclado;

        //removendo uma pessoa na lista de pessoas do sistema
        }


if (Opcao.equals(opcao3)){

        System.out.println("Digite o nome da pessoa que você quer pesquisar:");
        entradaTeclado = leitorEntrada.readLine();
        String umNome = entradaTeclado;

        //buscando pessoa na lista de pessoas


    }   
}
//conferindo saída
System.out.println("=================================");
System.out.println("=)");

}

}
  • 1

    Hello Rafael. Have you tried anything? Do you have any specific difficulty? It would be nice to share in your question what you have tried to do.

  • Well, I put to read from the keyboard a string that in the case was 1 to 4 and was comparing this string with strings defined from 1 to 4. If they were equal, it would execute the part of the corresponding code. But I don’t know at the end of that go back to the beginning to ask for a new string to be typed.

  • This question may sound silly, but your reading code is inside a loop (while, for example)? See, you’ll more easily get help from the community if you improve your question a little bit mainly by including the code you’ve already done. Makes it easier to understand its difficulty and stimulates the crowd to respond. :)

  • @Luizvieira sorry for the disorganization

  • Rafael, you must edit your question and put the code there, not in a comment. In fact, put the whole code (in your comment, for example, there is a variable called leitorEntrada that is not defined).

  • @Luizvieira now I put the whole code in my question, thank you since already for your help and attention.

  • I hope the answers help you, but see that your question is very specific (that is, a difficulty you have with the logic of programming) and so you can receive negative votes from the community. If that happens, don’t be discouraged from participating here. Try only in the future to ask the questions in as much detail as possible so that the community is really able to help you. :)

Show 2 more comments

2 answers

3

Well, come on. Your code has a few mistakes until common.

First, on line 25 (the loop condition) you are using:

while (Opcao != opcao4){

This condition will check whether the variable Opcao is different from the variable opcao4 in terms of its content, that is to say in practice if the objects are different. They will always be different because you have different strings. Then this loop will run endlessly. The ideal is to correct to compare the contents of the strings, not the objects themselves, as follows:

while (!Opcao.equals(opcao4)){

Another error is that your loop control variable is called Opcao but you don’t use it for reading the data! The variable you are using for reading the data is called entradaTeclado. So even with the previous fix your code will still not work properly. Thus, the code of line 25 would be more correct as follows:

while (!entradaTeclado.equals(opcao4)){

Regardless of these errors, there is a logic error in your loop. You start the program by displaying your "menu" of options and making an initial reading (the option itself). Then you enter the loop where the data of the specific option is requested. However, when this loop ends (and the execution returns to while), the option is not re-requested (it is there outside the loop, before it actually). Therefore, your code is eternally requesting the data of the first chosen option until (due to the previously suggested correction) it is interrupted by typing the number 4 (for example, make the corrections I suggested above and type 1 the first time you are prompted; you will notice that the code will only be terminated if you type in 4 on the person’s phone).

I must also say that your code is a little disorganized, and this may be clouding your own understanding. Try to correctly identify levels always, even within the class or function.

Another suggestion is that you do not need to put the option values in variables for comparison, because if (entradaTeclado.equals("1")){ is valid. Below I propose a code perhaps simpler that gets the result you want:

InputStream entradaSistema = System.in;
InputStreamReader leitor = new InputStreamReader(entradaSistema);
BufferedReader leitorEntrada = new BufferedReader(leitor);

String entradaTeclado;
do {
    System.out.println("Digite 1 para adicionar pessoa. Digite 2 para remover pessoa. Digite 3 para pesquisar uma pessoa. Digite 4 para sair.");
    entradaTeclado = leitorEntrada.readLine();      

    if(entradaTeclado.equals("1")) {
        System.out.println("Digite o nome da Pessoa:");
        String umNome = leitorEntrada.readLine();

        System.out.println("Digite o telefone da Pessoa:");
        String umTelefone = leitorEntrada.readLine();

        // Faz o que tem que fazer aqui
    }
    else if(entradaTeclado.equals("2")) {
        System.out.println("Digite o nome da pessoa que você quer remover:");
        String umNome = leitorEntrada.readLine();

        // Faz o que tem que fazer aqui
    }
    else if(entradaTeclado.equals("3")) {
        System.out.println("Digite o nome da pessoa que você quer pesquisar:");
        String umNome = leitorEntrada.readLine();

        // Faz o que tem que fazer aqui
    }
    else if(entradaTeclado.equals("4")) {
        break; // Interrompe
    }
    else {
        System.out.println("Oops! Opção inválida: " + entradaTeclado);
    }       
} while(true);

In that code I used the do...while instead of while because then you can make the value request first and only check the value at the end. In practice I put true for the verification as the value check 4 uses the break to interrupt. I also used else if to chain decisions so you can validate the invalid options on else final.

Note, however, that since your options are numerical the code can become more 'simple' if you convert the input to a number and use a switch. Note also that you do not need to read the data for the control variable entradaTeclado, nor should because it changes the value of the option. You can read immediately for the variables umNome and umTelefone.

1

You should read the input inside the repetition, example:

short entradaTeclado;
 do{
    //lê dado e realiza uma operação
    entradaTeclado = leitorEntrada.nextShort();
    switch(entradaTeclado){
        case 1: /*faz algo*/ break;
        case 2: /*faz algo*/ break;
        case 3: /*faz algo*/ break;
    }
 }while(entradaTeclado != 4);

Thus, while the user does not select the output option, it will repeat the loop.

  • Exactly what I was suggesting at the end of my reply (but I was too lazy to continue). hehe :)

  • I liked your answer better, more complete and explanatory, actually I was lazy and just typed the solution kk. As for the change in my code, I don’t think the last break is necessary, but it won’t change the execution :)

  • I think the two complement each other. About the last break, you are absolutely right. I only did it because I thought it would be simpler to understand the OP (if it bothered you, sorry, but can undo if you prefer) :)

  • I call no hehe ;)

Browser other questions tagged

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