这是菜单类
导入 java.util.Scanner;
公共类菜单 { 私有字符串 [] menu_options;
public Menu(String[] menu_options) {
this.menu_options = menu_options;
}
public int getUserInput() {
int i = 1;
for (String s : this.menu_options) {
System.out.println(i + ". " + s);
i++;
}
int selection = getint_input(menu_options.length);
return (selection);
}
private int getint_input(int max) {
boolean run = true;
int selection = 0;
while (run) {
System.out.print("Select an option: ");
Scanner in = new Scanner(System.in);
if (in.hasNextInt()) {
int value = in.nextInt();
if(value>=1 || value<=max){
selection = value; //fixed this now working
run = false;
}
} else {
System.out
.print("Invalid input. Please enter a integer between 1 and "
+ max + ": ");
}
}
return selection;
}
}
这是我使用的菜单驱动程序
公共类 Menutester {
public static void main(String[] args) {
String[] menuitems = new String[2];
menuitems[0] = "option one";
menuitems[1] = "option two";
Menu tm = new Menu(menuitems);
int choice = tm.getUserInput();
System.out.println("Got input");
}
}
我第一次输入它根本不注册的东西,当我尝试在 eclipse 中调试它时,它给了我错误 FileNotFoundException(Throwable).(String) line: 195 在第一个输入。
这就是它返回的内容
- 选项一
- 选项二 选择一个选项:1(我输入了这个并按下了回车键)1(这里相同,只是它注册了输入)得到了输入