0

这是菜单类

导入 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. 选项一
  2. 选项二 选择一个选项:1(我输入了这个并按下了回车键)1(这里相同,只是它注册了输入)得到了输入
4

2 回答 2

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;
   }
}
于 2013-02-01T02:29:20.340 回答
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);
}

再试一次。

于 2013-02-01T02:39:30.447 回答