簡體   English   中英

如何像在我的代碼中一樣將方法相互連接,當用戶按下 2 時,它將不得不去吃零食,但它會運行代碼來吃飯 java

[英]how to connect the methods to each other like in my code when the user press 2 it will have to go to snack but instead it runs the code to meals java

 import java.util.Scanner;
public class MP3
{

//這是我需要將每個方法連接到每個方法的主要代碼。 //這樣,如果用戶按 2,它就會去吃零食,但即使你現在按 2,它也會繼續執行代碼並去吃飯。 //我怎樣才能讓用戶可以選擇他/她喜歡瀏覽的菜單?

public static void main(String[] args)
      {
        int Options_Snacks;
        int Options_Snacks2;
        int Options_Snacks3;
        int Options_Drinks;
        int Options_Drinks2;
        int Options_Drinks3;
        int diff,prod ;
        int yes = 1;
        int no = 2;
        int End;
        
        
        do {
        mainmenu();
        mainmeals(); 
        mainsnacks();
       
        Scanner myInput = new Scanner(System.in);
        System.out.println("Would you like to order more: press " + yes +" for yes and " + no +" for no");
        End = myInput.nextInt();
        
        } while(End == 1);
      } 

// 此代碼運行流暢,但當用戶按下數字時,其他菜單不會運行,而是運行 while 循環中的所有代碼。

 public static void mainmenu()
        {
    
        int Orders;
        int Meals = 1;
        int Snacks = 2;
        int Drinks = 3;
        int EXIT = 4;
    
        Scanner myInput = new Scanner(System.in);
        System.out.println("=======[STRESSFOOD]=====");
        System.out.println("---------[ Menu ]-------");
        System.out.println("1----------Meals--------");
        System.out.println("2---------Snacks--------");
        System.out.println("3---------Drinks--------");
        System.out.println("4--------[ EXIT ]-------");
        Orders = myInput.nextInt();
    
       
       }
    [here's the code I didn't get all in the picture][1]
    }

下面的實現怎么樣:

public static void main(String[] args) {
        openMenu();
}

使用菜單功能中的while循環:

private static void openMenu() {
        Scanner scan = new Scanner(System.in);

        do {

            System.out.println("1) Meals");
            System.out.println("2) Snacks");
            System.out.println("3) Drinks");
            System.out.println("4) Exit");
            System.out.print("Your choice ? ");

            switch (scan.nextInt()) {
                case 1:
                    openMealsMenu();
                    break;
                case 2:
                    openSnacksMenu();
                    break;
                case 3:
                    openDrinksMenu();
                    break;
                case 4:
                    scan.close();
                    return;
                default:
                    System.out.println("This is not a valid choice");
            }
        } while (true);

    }

請注意,您的應用程序中應僅使用一台掃描儀。 例如,如果您需要在 openMealsMenu() 中使用掃描儀,請將其作為方法的參數傳遞,或者僅在 MP3 類中聲明一個靜態掃描儀,因為您的方法在同一類中。

順便說一下,按照慣例,變量應該以小寫字母開頭並且不帶_ (即Options_Drinks3變成optionsDrinks3 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM