用 Java 在 Eclipse 中做一个程序。我想要做的是当我执行我想要的程序时向用户提供一个选择。我已经完成了所有的计算等,我只是不确定如何制作这个菜单来为用户提供选择。我正在寻找的示例:
To enter an original number: Press 1
To encrypt a number: Press 2
To decrypt a number: Press 3
To quit: Press 4
Enter choice:
public static void main(String[] args) {
Data data = new Data();
data.menu(); }
}
最佳答案
为了简单起见,我建议使用返回选项的整数值的静态方法。
public static int menu() {
int selection;
Scanner input = new Scanner(System.in);
/***************************************************/
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Enter an original number");
System.out.println("2 - Encrypt a number");
System.out.println("3 - Decrypt a number");
System.out.println("4 - Quit");
selection = input.nextInt();
return selection;
}
完成该方法后,您将在主方法中相应地显示它,如下所示:
public static void main(String[] args) {
int userChoice;
/*********************************************************/
userChoice = menu();
//from here you can either use a switch statement on the userchoice
//or you use a while loop (while userChoice != the fourth selection)
//using if/else statements to do your actually functions for your choices.
}
希望这对您有所帮助。
关于java - 创建一个控制台菜单供用户进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8059259/