如何循环回到Java *初学者编码器*中的主菜单

时间:2019-05-18 09:25:14

标签: java loops netbeans

我正在尝试使用while循环返回到主菜单,但我无法     似乎可以正常工作。如何正确实施?

我尝试了do-while循环一会儿,但没有用。我正在做     有问题,我不知道是什么

boolean main_menu = true;
while (main_menu) {


    System.out.println("       Welcome to Zoos Victoria          ");
    System.out.println("        M A I N        M E N U           ");
    System.out.println(" Zoo has the following ticketing options:");
    System.out.println("         1 = Child (4-5 yrs)             ");
    System.out.println("         2 = Adult (18+ yrs)             ");
    System.out.println("      3 = Senior (60+ yrs) "  +  "\n"     );

    do {
    // select ticket option
    System.out.println(" Please enter your option:"     );
    ticket_option = input.nextInt();

        switch (ticket_option) {

            // Child_ticket
            case 1: 
                ticket_price = child_ticket; 
                ticket_name = " Child tickets";
                break; 

            // adult ticket
            case 2:  
                ticket_price = adult_ticket;
                ticket_name = " Adult tickets";
                break;

            //senior ticket 
            case 3:
                ticket_price = senior_ticket;
                ticket_name = " Senior tickets";
                break;  
            default:    
                System.out.println("Invalid entry!");
        } 

    } while( ticket_option > 3); //end of do while loop


    System.out.println("    Enter the number of tickets you would like:");
    ticket_amount = input.nextInt();
    total_price = ticket_amount * ticket_price;

    System.out.println(" you are purchasing " + ticket_amount + 
           ticket_name + " at " + "$"+ticket_price  + " each!");

    System.out.println(" Press 1 to confirm purchase"); 
    confirm_purchase = input.nextInt();

    if (confirm_purchase == 1)
        System.out.println("Total amount payable: "+ "$"+total_price);  
    else {  
        System.out.println("invalid key!");           
        main_menu = false;
    }   
      if (confirm_purchase == 1 ) {
System.out.println("Total amount payable: "+ "$"+total_price);  
    main_menu = false;
} else {            
        System.out.println("invalid key!");
        }

   System.out.println("Would you like to go back to the main menu?(Y/N) ");
   to_continue = input.next().toUpperCase();

   if (to_continue.equals("Y")){
     // back to main menu here
       System.out.println("Back to the main menu");

   }  else {
       System.out.println("Total amount payable: "+ "$"+total_price);
       System.out.println("Have a great time!");


   }
}// end while loop

} }

在if语句中,用户将按1,否则,程序将返回到主菜单。目前,这无法正常工作。

1 个答案:

答案 0 :(得分:0)

在您确认购买的条件下,如果用户输入了无效的密钥,则会将main_menu设置为false。您应该将其删除。

if (confirm_purchase == 1) {
System.out.println("Total amount payable: "+ "$"+total_price);  
} else {  
      System.out.println("invalid key!");           
             // main_menu = false; 
}