Java get integer输入法需要输入两次

时间:2013-02-01 02:23:21

标签: java input

这是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。

这是它返回的内容

  1. 选项一
  2. 选项二 选择一个选项:1(我输入了这个并按下回车键) 1(这里只是它重新输入了输入) 得到了输入

2 个答案:

答案 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);
}

再试一次。