这是Menu类
import java.util.Scanner;
public class Menu { private String [] 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;
}
}
这是我正在使用的menudriver
公共类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");
}
}
我第一次输入的内容根本没有regester,当我尝试在eclipse中调试它时,它给出了错误FileNotFoundException(Throwable)。(String)line:195 on first input。
这是它返回的内容
答案 0 :(得分:4)
nextInt
读取输入并将其从缓冲区中删除。如果不存储值,就无法像这样调用它。
调用一次,存储值,然后进行所需的所有检查。
改变这个:
if (in.hasNextInt() && in.nextInt() >= 1 || in.nextInt() <= max) {
selection = in.nextInt();
//...
为此:
if(in.hasNextInt()) {
int selection = in.nextInt();
if(selection >= 1 || selection <= max) {
run = false;
}
}
答案 1 :(得分:1)
取代:
if (in.hasNextInt() && in.nextInt() >= 1 || in.nextInt() <= max) {
selection = in.nextInt();
run = false;
System.out.println(run);
}
为:
int input = in.nextInt();
if (input >= 1 || input <= max) {
selection = in.nextInt();
run = false;
System.out.println(run);
}
再试一次。