如何再次打印菜单

时间:2016-01-05 21:17:48

标签: java

如何使用下面的代码返回我的菜单选择? 程序输出后,如何再次返回菜单?

import java.util.*;
import java.util.Scanner;
public class Meme {
    public static void main(String[] args)
    {
        Scanner inp= new Scanner(System.in);
        int choose;
        System.out.println("Enter your selection:\n1 for Addition\n2 for substraction \n3 for Multiplication\n4 for division");

        choose = inp.nextInt();

        int num1,num2;
        int ans;
        System.out.println("Enter first number:");
        num1 = inp.nextInt();
        System.out.println("Enter second number:");
        num2 = inp.nextInt();


        switch (choose){
        case 1:
            System.out.println(add( num1,num2));
            break;
        case 2:
            System.out.println(sub( num1,num2));
            break;      
        case 3:
            System.out.println(mult( num1,num2));
            break;
        case 4:
            System.out.println(div( num1,num2));
            break;
            default:
                System.out.println("Illigal Operation");


        }



    }
    public static int add(int x, int y)
    {
        int result = x + y;
        return result;

    }
    public static int sub(int x, int y)
    {
        int result = x-y;
        return result;
    }
    public static int mult(int x, int y)
    {
        int result = x*y;
        return result;
    }
    public static int div(int x, int y)
    {
        int result = x/y;
        return result;
    }

}

程序输出后,如何再次返回菜单?

1 个答案:

答案 0 :(得分:3)

有一个while循环包装菜单和switch语句。在菜单中添加退出条件,如果用户输入特定值,则返回。

有些内容(我假设用户的任何其他输入作为退出信号,您可以根据需要进行更改):

public static void main(String[] args) {
    Scanner inp = new Scanner(System.in);
    int choose;

    while (true) {
        System.out.println(
                "Enter your selection:\n1 for Addition\n2 for substraction \n3 for Multiplication\n4 for division\nExit: Any other input");

        choose = inp.nextInt();

        int num1, num2;
        int ans;
        System.out.println("Enter first number:");
        num1 = inp.nextInt();
        System.out.println("Enter second number:");
        num2 = inp.nextInt();

        switch (choose) {
        case 1:
            System.out.println(add(num1, num2));
            break;
        case 2:
            System.out.println(sub(num1, num2));
            break;
        case 3:
            System.out.println(mult(num1, num2));
            break;
        case 4:
            System.out.println(div(num1, num2));
            break;
        default:
            return;

        }
    }
}