Do while Loop to show a menu

给你一囗甜甜゛ 提交于 2020-12-31 20:01:33

问题


I have created my menu with do~while(true); but every time the user insert a number, instead of running the program it shows the the menu again! what do you think?

// my main method

public static void main(String[] args) {

    DataReader reader = new DataReader(); // The reader is used to read data from a file

    // Load data from the file
    if(reader.loadData(args[0])) {          // The filename is entered using a command-line argument

        vehicles= reader.getVehicleData(); // Store the arrays of Vehicle

        // Display how many shapes were read from the file
        System.out.println("Successfully loaded " + vehicles[0].getCount() + 
                           " vehicles from the selected data file!");
        displayMenu();
    }
}

// dispaly menu method

private static void displayMenu() {
    Scanner input = new Scanner(System.in);

    do {
        System.out.println("\n\n          Car Sales Menu");
        System.out.println("--------------------------------------");
        System.out.println("1 - Sort vehicles by owner's Last Name");
        System.out.println("2 - Sort vehicles by vehicle Model");
        System.out.println("3 - Sort vehicles by vehicle Cost\n");
        System.out.println("4 - List All Vehicles");
        System.out.println("5 - List All Cars");
        System.out.println("6 - List American Cars Only (Formal)");
        System.out.println("7 - List Foreign Cars only (Formal)");
        System.out.println("8 - List All Trucks");
        System.out.println("9 - List All Bicycles");
        System.out.print("\nSelect a Menu Option: ");
        getInput(input.next()); // Get user input from the keyboard 
    }
    while(true); // Display the menu until the user closes the program
}

// getInput method

private static void getInput(String input) {
    switch(Convert.toInteger(input)) {
        case 1: // Sort Vehicles by Owner's Last Name
            Array.sortByOwnerName(vehicles);
            break;
        case 2: // Sort Vehicles by Vehicle Make & Model
            Array.sortByVehicleMakeModel(vehicles);
            break;
        case 3: // Sort Vehicles by Vehicle Cost
            Array.sortByVehicleCost(vehicles);
            break;
        case 4: // List All Vehicles
            displayVehicleData(0);
            break;

        default:
            System.out.print("The entered value is unrecognized!");
            break;
    }
}

回答1:


Because you have while(true);, this means that the menu it will be in a infinite loop until a break is call.

Try to do something like:

 do {
        System.out.println("\n\n          Car Sales Menu");
        System.out.println("--------------------------------------");
        System.out.println("1 - Sort vehicles by owner's Last Name");
        System.out.println("2 - Sort vehicles by vehicle Model");
        System.out.println("3 - Sort vehicles by vehicle Cost\n");
        System.out.println("4 - List All Vehicles");
        System.out.println("5 - List All Cars");
        System.out.println("6 - List American Cars Only (Formal)");
        System.out.println("7 - List Foreign Cars only (Formal)");
        System.out.println("8 - List All Trucks");
        System.out.println("9 - List All Bicycles");
        System.out.print("\nSelect a Menu Option: ");
    try {
        int input = Integer.parseInt(getInput(input.next())); // Get user input from the keyboard 


        switch (input) {
        case 1:  // do something
                 break;
        case 2:  // do something
                 break;
        ...
       }
      } catch (NumberFormatException e) { ... }

    }
    while(true); // Display the menu until the user closes the program

You can use switch to process the input, and depending on input do the respective action.




回答2:


while(true); // Display the menu until the user closes the program

while true doesn't mean exactly the thing that you have written in comment. You need to add some other condition in your while loop to check that condition. That condition should be on the input you read from the user.

For e.g, something like this. Note that this might not completely solve your problem, as there seems to be some other issues also with your code: -

int userInput = 0;
do {
    try {
        userInput = Integer.parseInt(getInput(input.next()));
    } catch (NumberFormatException e) {
        userInput = 0;
    }

} while (userInput < 1 || userInput > 9);

return userInput;  // For this you need to change return type of `displayMenu()`

And then, process the userInput returned in your main() method. There you would need to store the return value in some local variable.

int userInput = displayMenu();



回答3:


Because your while loop is while(true) it will always keep looping until the program is forcefully broken. Without the content of your getInput() function, all that can be said is that the loop will never end.

You will need to handle your user's input, either in the getInput() method or after using it, and then conditionally break out of the while(true) when certain criteria are met.




回答4:


Assuming your getInput method does what it says it does, you haven't actually done anything with your input once it has been read in.

So when the user enters a value, your program reads the value, happily ignores it, and then runs the menu again.



来源:https://stackoverflow.com/questions/13536206/do-while-loop-to-show-a-menu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!