简体   繁体   中英

My program is no taking the user input to start the program over in a loop

I have a loop that start the program over if the user input is yes and end the program if the user input is no

my codes end the program when the user input is no but if its any thing else it will start over i want to make it only start over if the user input is yes

 System.out.println("Would you like to purchase more ticket ? ");
    Scanner answer = new Scanner(System.in);
    String an = answer.nextLine();
    if (an.equals("yes"))
    {
      lottery =true;
    }
    else if(an.equals("no"))
    {
      System.out.println("Thank you, Have a Great Day"); 
      lottery=false;
    }

Having a logical guess, I'd say that the boolean is always going to be true, until you enter "no", because it is first initialised as true, therefore if both of the if statements fail, it will still be true, thus it will continue to iterate through the loop. Just remove the if statement for the no condition. In fact, you could also remove the boolean by using an infinite loop, and if the user enters yes, just use the continue keyword to complete the iteration, otherwise break out of the loop.

while(true) {
    System.out.println("Would you like to purchase more ticket?");
    Scanner answer = new Scanner(System.in);
    String an = answer.nextLine();
    if (an.equals("yes")) {
        continue;
    }
    System.out.println("Thank you, Have a Great Day");
    break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM