1

对于 Java 中的控制台菜单,我有时想读取整数和一些字符串。我有这两个功能:

获取字符串:

public String enterString(String question) {
    System.out.println(question);
    return scanner.nextLine();
}

要获得一个 int(稍后用于 switch 语句):

public int choose(int b, String question) {
    Boolean chosen = false;     
    while(!chosen) {
        chosen = true;
        System.out.println(question);
        int choice = scanner.nextInt();

        if(choice >= 0 && choice <= b) {
            return choice;
        }
        else {
            chosen = false;
            System.out.println("Not a valid choice.");
        }
    }
    return 0; //the compiler complains otherwise
}

但是,如果我enterString()先使用然后choose()enterString()使用,它​​似乎使用了选择中的换行符。scanner.nextLine()在不同的地方(每个功能的开始和结束)输入总是会引起问题。

我怎样才能使两者的任何组合起作用?

4

2 回答 2

3

nextInt()不会消耗 EOL。所以,要么扫描Int

 int choice = Integer.parseInt(scanner.nextLine());

或者,消耗额外的新行

 int choice = scanner.nextInt();
 scanner.nextLine(); // Skip
于 2013-07-02T09:31:32.843 回答
1

scanner.nextInt() 不消耗行尾。您可以将 nextLine 包装在一个 while 循环中,如果该行为空,则再次要求输入。

于 2013-07-02T09:29:51.267 回答