我不确定我是否也正确使用了公共静态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.Additionn2.Subtractionn3.ExitnnSelect Menu(1-3): ");
Scanner kb = new Scanner(System.in);
int choice = kb.nextInt();
return choice;
}
代码大部分已经完成。要将其放入循环中,请使用while(true)
:
public static void main(String[] args) {
while (true) {
int choice = mm();
// rest of method
退出时,不要使用退出switch
块的break;
,而是使用完全退出程序的System.exit(0);
。
这样的东西就足够了:
while( true )
{
// Display menu and let user pick one choice.
switch( choice )
{
// Other cases till here.
default: exit.
}
}