-1

我不确定我是否也正确使用了 public static int 。总而言之,我觉得这段代码是一团糟至。

import java.util.Scanner;

public class Program7 {

    public static void main(String[] args) {
        // main menu
        mm();

        int choice = 0;
        switch (choice) {
            // addition
            case 1:
                add();  
                break;

            // subtraction
            case 2:
                sub();
                break;

            // exit
            case 3:
                System.out.print("GOOD BYE ^__^");  
                break;

            // if choice >3 or <1
            default:
                System.out.print("\nInvalid selection.\nPlease select from (1-3): ");
                Scanner kb = new Scanner(System.in);
                choice = kb.nextInt();
        }
   }

添加

public static int add() {
    System.out.print("\nEnter number1: ");
    Scanner kb = new Scanner(System.in);
    int num1 = kb.nextInt();

    System.out.print("Enter number2: ");
    int num2 = kb.nextInt();
    int sum = num1 + num2;

    System.out.print("\n" + num1 + " + " + num2 + " = " + sum);
    return sum; 
}

减法

public static int sub() {
    System.out.print("Enter number1: ");
    Scanner kb = new Scanner(System.in);
    int num1 = kb.nextInt();

    System.out.print("Enter number2: ");
    int num2 = kb.nextInt();
    int diff = num1 - num2;

    System.out.print(num1 + " - " + num2 + " = " + diff);
    return diff;
}

无效数字(<1 或 >3)的主菜单和/或在用户完成选择后直到他们选择选择数字 3:

public static int mm() {
    System.out.print("==MAIN MENU==\n1.Addition\n2.Subtraction\n3.Exit\n\nSelect Menu(1-3): "); 
    Scanner kb = new Scanner(System.in);
    int choice = kb.nextInt();
    return choice;
}
4

2 回答 2

1

代码大部分都完成了。要将其置于循环中,请使用while(true)

public static void main(String[] args) {
    while (true) {
        int choice = mm();
        // rest of method

退出时,不要使用break;which 退出switch块,而是使用System.exit(0);which 完全退出程序。

于 2015-11-03T16:55:19.213 回答
0

像这样的东西就足够了:

while( true )
{
    // Display menu and let user pick one choice.
    switch( choice )
    {
        // Other cases till here.
        default: exit.
    }
}
于 2015-11-03T16:56:57.747 回答