java 使用案例后如何制作Java主菜单循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34928182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:33:37  来源:igfitidea点击:

How to make a Java Main Menu Loop after using a case

javaloopsmenuswitch-statement

提问by Ace Ebert

I am pretty dang new to Java, but being familiar with some other programming languages, I know the basic lay out of a lot of it. One thing I am struggling with is looping menus, specifically a main menu.

我对 Java 非常陌生,但熟悉其他一些编程语言,我知道其中很多的基本布局。我正在努力解决的一件事是循环菜单,特别是主菜单。

I have tirelessly researched methods of it, but none seem to apply or work to my program. I'm assuming its something silly and small that I'm missing in my more-so basic program.

我不知疲倦地研究了它的方法,但似乎没有一种方法适用于或适用于我的程序。我假设我的基本程序中缺少它一些愚蠢和小的东西。

Check it below, thanks for any tips.

检查下面,感谢您的任何提示。

    import java.util.Scanner;
public class basicCalc {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);
        boolean mainLoop = true;

        int choice;
        do{
            System.out.println("Calculator Main Menu\n");
            System.out.print("1.) Addition \n");
            System.out.print("2.) Subtraction.\n");
            System.out.print("3.) Multiplication.\n");
            System.out.print("4.) Division.\n");
            System.out.print("5.) Generate Random Number.\n");
            System.out.print("6.) Exit\n");
            System.out.print("\nEnter Your Menu Choice: ");

            choice = input.nextInt();


        }

        while(choice >7);

        switch(choice){

        case 1:
            //Definitions
            int adNumf, adNuml, sum;
            System.out.print("Please Enter The First Number: ");
            adNumf = input.nextInt();
            System.out.print("\nPlease Enter The Second Number: ");
            adNuml = input.nextInt();
            sum = adNumf + adNuml;
            System.out.print("The Sum Of Those Numbers is: " +sum);
            break;

        case 2: 
            int subNum1, subNum2, sum2;
            System.out.println("\nPlease Enter The First Number: ");
            subNum1 = input.nextInt();
            System.out.println("Please Enter The Second Number: ");
            subNum2 = input.nextInt();
            sum2 = subNum1 - subNum2;
            System.out.println("The Subtraction Leaves The Number: " +sum2);
            break;

        case 3:
            int multNum1, multNum2, multTotal;

            // Gather Input
            System.out.println("Please Enter The First Number To Multiply: ");
            multNum1 = input.nextInt();
            System.out.println("Please Enter The Second Number To Multiply: ");
            multNum2 = input.nextInt();

            // This will Multiply the Numbers
            multTotal = multNum1 * multNum2;

            //Display Final
            System.out.println("The Multiplied Numbers Are: " +multTotal);
            break;

        case 4: 
            //Definitions
            double divNum1, divNum2, divTotal;
            System.out.println("Enter Your Numerator ");
            divNum1 = input.nextInt();
            System.out.println("Enter Your Denominator ");
            divNum2 = input.nextInt();
            if(divNum2 == 0){
                System.out.println("Zero is Not divisable, please select a new denominator: ");
                divNum2 = input.nextInt();
            }
            divTotal = divNum1 / divNum2;
            System.out.println("Your divisor is: " +divTotal);
            break;

        case 5:
            double limL, limH, rand;
            System.out.println("Enter Your Low Limit: ");
            limL = input.nextInt();
            System.out.println("Enter Your High Limit ");
            limH = input.nextInt();

            //Equation to keep numbers within bounds
            rand = limL + (Math.random() * ((limH - limL) + 1));
            System.out.println("Given Your Limits, the Random Number will be: " +rand);
            break;

        case 6: 
            System.out.println("Exiting Program...");
            System.exit(0);
             break;
        }



        // Bad Menu Option Direct
    if (choice > 6 || choice < 1){
        System.out.println("This is not a valid Menu Option! Please Select Another.");
        do{
            choice = input.nextInt();
        }
        while(choice < 7 );
    }
    // End bad menu option  


    }

}

回答by Jimmy M.

You have a general idea of what to do, however you are making your loop ending condition more complicated than it needs to be. Try a "default" option to catch any input out of the range. That way you can simplify your ending condition to just "6" (the exit case). To show simply:

您对要做什么有一个大致的了解,但是您使循环结束条件比需要的更复杂。尝试使用“默认”选项来捕获超出范围的任何输入。这样您就可以将结束条件简化为“6”(退出情况)。简单地显示:

do{
  //Menu options
  System.out.print("6.) Exit\n");
  System.out.print("\nEnter Your Menu Choice: ");

  choice = input.nextInt();

  switch(choice){
        //Your cases from 1 to 6.
        default:
            System.out.println("Invalid menu choice; try again.");
            break;
   }
}while(choice != 6);

Whatever follows default will be called if the choice option is not for any of the cases create in your code.

如果选择选项不适用于您的代码中创建的任何案例,则将调用默认值之后的任何内容。

回答by The Law

Your whole execution flow is wrong. You should put the bad menu choice check (in your case the if) before the cases. And to have infinite menu loop, just add another ifthat breaks the infinite while-loop.

你的整个执行流程是错误的。您应该将错误的菜单选择检查(在您的情况下if)放在案例之前。并有无限菜单循环,只需添加另一个if打破无限的while-loop

Pseudo code:

伪代码:

while(true){
//enter your choice, 8 to exit
  if(choice != valid_range){
//error message
  }
switch(choice){
  case 1: //code
  case 2: //code
  .
  .
  .
  case 7: //code
   if (choice == 8) {
break; //will give flow control to next element after the while statement
   }    
 }
}

回答by Anoop LL

You can give whole code(from displaying menu) inside a while loop and give condition as true so that after using a case it will automatically repeat(as you are using 6 to EXIT). And if any invalid input is given for eg:10 the case will go to default section and will execute the code there

您可以在 while 循环中提供整个代码(来自显示菜单)并将条件设为 true,以便在使用案例后它会自动重复(因为您使用 6 退出)。如果为 eg:10 提供任何无效输入,则案例将转到默认部分并在那里执行代码

import java.util.Scanner;
public class basicCalc {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner input = new Scanner(System.in);
    boolean mainLoop = true;

    int choice;
    while(true){
        System.out.println("Calculator Main Menu\n");
        System.out.print("1.) Addition \n");
        System.out.print("2.) Subtraction.\n");
        System.out.print("3.) Multiplication.\n");
        System.out.print("4.) Division.\n");
        System.out.print("5.) Generate Random Number.\n");
        System.out.print("6.) Exit\n");
        System.out.print("\nEnter Your Menu Choice: ");

        choice = input.nextInt();




    switch(choice){

    case 1:
        //Definitions
        int adNumf, adNuml, sum;
        System.out.print("Please Enter The First Number: ");
        adNumf = input.nextInt();
        System.out.print("\nPlease Enter The Second Number: ");
        adNuml = input.nextInt();
        sum = adNumf + adNuml;
        System.out.print("The Sum Of Those Numbers is: " +sum);
        break;

    case 2: 
        int subNum1, subNum2, sum2;
        System.out.println("\nPlease Enter The First Number: ");
        subNum1 = input.nextInt();
        System.out.println("Please Enter The Second Number: ");
        subNum2 = input.nextInt();
        sum2 = subNum1 - subNum2;
        System.out.println("The Subtraction Leaves The Number: " +sum2);
        break;

    case 3:
        int multNum1, multNum2, multTotal;

        // Gather Input
        System.out.println("Please Enter The First Number To Multiply: ");
        multNum1 = input.nextInt();
        System.out.println("Please Enter The Second Number To Multiply: ");
        multNum2 = input.nextInt();

        // This will Multiply the Numbers
        multTotal = multNum1 * multNum2;

        //Display Final
        System.out.println("The Multiplied Numbers Are: " +multTotal);
        break;

    case 4: 
        //Definitions
        double divNum1, divNum2, divTotal;
        System.out.println("Enter Your Numerator ");
        divNum1 = input.nextInt();
        System.out.println("Enter Your Denominator ");
        divNum2 = input.nextInt();
        if(divNum2 == 0){
            System.out.println("Zero is Not divisable, please select a new denominator: ");
            divNum2 = input.nextInt();
        }
        divTotal = divNum1 / divNum2;
        System.out.println("Your divisor is: " +divTotal);
        break;

    case 5:
        double limL, limH, rand;
        System.out.println("Enter Your Low Limit: ");
        limL = input.nextInt();
        System.out.println("Enter Your High Limit ");
        limH = input.nextInt();

        //Equation to keep numbers within bounds
        rand = limL + (Math.random() * ((limH - limL) + 1));
        System.out.println("Given Your Limits, the Random Number will be: " +rand);
        break;

    case 6: 
        System.out.println("Exiting Program...");
        System.exit(0);
         break;
    default :
             System.out.println("This is not a valid Menu Option! Please Select Another");
             break;

    }


    }




    }

   }

回答by Daniel Stiefel

or try thisone

或者试试这个

import java.util.Scanner;
public class basicCalc {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);
        boolean mainLoop = true;

        int choice;
        do{
            System.out.println("Calculator Main Menu\n");
            System.out.print("1.) Addition \n");
            System.out.print("2.) Subtraction.\n");
            System.out.print("3.) Multiplication.\n");
            System.out.print("4.) Division.\n");
            System.out.print("5.) Generate Random Number.\n");
            System.out.print("6.) Exit\n");
            System.out.print("\nEnter Your Menu Choice: ");
            choice = input.nextInt();




        switch(choice){

        case 1:
            //do something
            break;

        case 2: 
            //do something
            break;

        case 3:
            //do something
            break;

        case 4: 
            //do something
            break;

        case 5:
            //do something
            break;

        case 6: 
            System.out.println("Exiting Program...");
            System.exit(0);
             break;
        default:
        System.out.println(choise + " is not a valid Menu Option! Please Select Another.");

    }while(choice != 6 /*Exit loop when choice is 6*/);



    }

}