Method is running 3 times

Asked

Viewed 78 times

-3

I created this method for a validation when the user will type the option that appears on the screen:

private int menu;
private int menuImprimir;

public int getMenu() 
    {
        return menu;
    }
    public void ativarStatus() 
    {
        this.status = "Ativado";
    }

   public void menuImprimir() 
    {
        System.out.println("Deseja Imprimir os dados?" +
                "\n1 - Sim" + 
                "\n2 - Não");       
                this.menuImprimir = input.nextInt(); 

                while(this.menuImprimir < 1 || this.menuImprimir > 2) 
                {
                    System.out.println("\nErro! - Digite uma opção válida");

                    menuImprimir();
                }

                switch(this.menuImprimir) 
                {
                case 1:
                    imprimir();
                    break;
                case 2:
                    System.out.println("Obrigado! ... ");
                    break;
                default:
                    System.out.println("Opção inválida!\nDigite novamente: ");
                    break;
                }
    }

If the client type the option other than 0 and 1 it stays inside the while asking him to enter the correct option. But if the client type 3 times the wrong option and on the fourth he type the correct system is printing System.out.println("Concluído com Sucesso!");"3 times to later exit the method, even if I put this Return..

  • Please provide a code that is a [mcve] so that it is possible to test.

  • 1

    The method does exactly what is asked. Repeat until the user enters a valid option; in that case it exits.

  • @Articuno I put the whole method as requested.. Note that when I call the menuImprimir() method, a message appears and stores a value in the menuImprimir variable, I type the invalid option 3x and the 3 times it enters the while and calls the menuImprimir() method again, in the 4ºx I type the right one, it jumps the while and enters the switch. So if I typed 2, it should appear message 2 finish the method. Only it appears the message and back to compare the while again, passes from while pq the option typed is 2, print again and back, repeating this process for more 2x

1 answer

2


I’ll guess what the method getMenu ago:

  • writes the options
  • asks the user to enter a number
  • le and returns the number typed

Then, every time it is called, it will require a new digit. On that line while(getMenu() < 0 || getMenu() > 1) will ask for the digit for the first time and compare it to zero. If it is not smaller, it will ask for a second digit to compare with 1. And, within the loop, the method is called by third time. It’s definitely not what you want to do...

The response of the first call must be stored in a variable for then the content of that being compared, ie the method is called only once... only being called again when a new value is listed.

Example, very much simplified (using the question code structure):

int menu = getMenu();
while (menu < 0 || menu > 1) {
    System.out.println(MENSAGEM_ERRO);
    if (menu == 0) {
        ...
        return;
    }
    if (menu == 1) {
        ...
        return;
    }
    ...

    menu = getMenu();
}

A little better structure would be:

while (true) {
    int menu = getMenu();
    if (menu == 0) {
        ...
        return;
    }
    if (menu == 1) {
        ...
        return;
    }
    System.out.println(MENSAGEM_ERRO);
}

(a little) More 'advanced'' :

int menu;
while ((menu = getMenu()) < 0 || menu > 1) {
    System.out.println(MENSAGEM_ERRO);
}
switch (menu) {
    case 0:
        ...
        break;
    case 1:
        ...
        break;
    default: throw IllegalArgumentException("Error menu: " + menu);
}

Other, better option (IMHO): the method getMenu test the given value, only returning valid values...

  • Carlos, I just took advantage of the switch part, I didn’t use the while pq would fall into infinite loop... I had forgotten the switch... You could use the default to call up the menu again in case of this error.. Vlw

  • Carlos, I thought it worked. But it didn’t.

  • The is basically the same validation, I made 2 validations one for the Print Menu and the other the Main Menu. I used the same structure. But I was able to find the bug. I used the switch using case1 and case 2 and the end used only 1 if. Thanks for the help!

Browser other questions tagged

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