Java Scanner.nextLine() 不等待输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12124793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:40:44  来源:igfitidea点击:

Java Scanner.nextLine() not waiting for input

java

提问by floppsb

I have several methods that I've used previously to accept user input and return it as a certain data type to the method that calls for it. I have used these methods, or variations of them, in previous projects.

我以前使用过几种方法来接受用户输入并将其作为特定数据类型返回给调用它的方法。我在以前的项目中使用过这些方法或它们的变体。

I've adopted the method that I used for string to select the first char given and return that, so that I can use this in a menu. Every time I start the application, the main menu appears and waits for user input. After receiving this input, the program loops continuously until stopped. Here is my method for capturing the char:

我采用了用于字符串的方法来选择给定的第一个字符并返回它,以便我可以在菜单中使用它。每次启动应用程序时,都会出现主菜单并等待用户输入。接收到这个输入后,程序会不断循环直到停止。这是我捕获字符的方法:

private char getUserChar(String prompt) {
    try {
        Scanner scan = new Scanner(System.in);
        System.out.print(prompt);
        String tempString = "";
        tempString = scan.nextLine();
        scan.close();
        char userChar = tempString.charAt(0);
        return userChar;
    } catch(Exception ex) {
        System.out.println(ex.getMessage());
    }
    return 0;
}

The code loops due to the try/catch block, as scan.nextLine() never waits for the next input. Without it, the exception is typically related to not finding a new line. I've tried the while(scan.hasNextLine()) that seems to work for other people; however, once the time for input arrives, it never breaks out of the loop. I also don't believe I'm tripping up on the nextInt() issue that everyone seems to have troubles with. I'll post the code for the entire class below:

由于 try/catch 块,代码循环,因为 scan.nextLine() 从不等待下一个输入。没有它,异常通常与找不到新行有关。我已经尝试过似乎对其他人有效的 while(scan.hasNextLine()) ;然而,一旦输入时间到了,它就永远不会跳出循环。我也不相信我在 nextInt() 问题上绊倒了每个人似乎都遇到了麻烦。我将在下面发布整个课程的代码:

import java.util.Scanner;
import controller.Controller;
public class TUI {
    private Controller controller;
    public TUI() {
        Controller controller = new Controller();
        this.controller = controller;
    }

    public void run() {
        boolean wantToQuit = false;
        char userInput = 0;
        System.out.println("Welcome to the Mart.");
        do{
            userInput = mainMenu();
            if(isUserInputValid(userInput))
                switch(userInput){
                    case 'a': addItem();
                    break;
                    case 'r': controller.removeItem();
                    break;
                    case 'i': controller.printInventory();
                    break;
                    case 'p': controller.customerPurchase();
                    break;
                    case 'w': controller.weeklyStock();
                    break;
                    case 'c': wantToQuit = true;
                    break;
                }
            else System.out.println("\nMainMenu");



        } while(!(wantToQuit));
        System.out.println("WolfMart is now closed.  Thank you and good-bye.");
    }




    private boolean isUserInputValid(char userInput) {
        char[] testSet = {'a', 'r', 'i', 'p', 'c', 'w'};
        for(char currentChar : testSet) {
            if(currentChar == userInput)
                return true;
        }
        return false;
    }

    private char mainMenu() {
        System.out.println();
        controller.printInventory();
        String mainMenuSelection = "What would you like to do: (a)dd item, (r)emove item, print (i)nventory, " +
            "(p)urchase by customer, (c)lose store?\r\n";

        char mainMenuInput = getUserChar(mainMenuSelection);
        return mainMenuInput;
    }

    private char getUserChar(String prompt) {
        try {
            Scanner scan = new Scanner(System.in);
            System.out.print(prompt);
            String tempString = "";
            tempString = scan.nextLine();
            scan.close();
            char userChar = tempString.charAt(0);
            return userChar;
        } catch(Exception ex) {
            System.out.println(ex.getMessage());
        }
        return 0;
    }


    private int getUserInt(String prompt) {
        Scanner scan = new Scanner(System.in);
        int userInt = -1;
        try {
            System.out.print(prompt);
            String input = scan.nextLine();
            userInt = Integer.parseInt(input);
        }
        catch(NumberFormatException nfe) {
            System.out.println("I did not recognize your command, please try again.");
        }
        scan.close();
        return userInt;
    }

    private String getUserString(String prompt) {
        Scanner scan = new Scanner(System.in);
        String userString = null;
        try{
            System.out.print(prompt);
            userString = scan.nextLine();
        } catch(Exception ex)
        {
            System.out.println("I did not recognize your command, please try again.");
        }
        scan.close();
        return userString;
    }

    private double getUserDouble(String prompt) {
        Scanner scan = new Scanner(System.in);
        double userDouble = -1.0;
        try {
            System.out.print(prompt);
            String input = scan.nextLine();
            userDouble = Double.parseDouble(input);
        }
        catch(NumberFormatException nfe) {
            System.out.println("I did not recognize your command, please try again.");
        }
        scan.close();
        return userDouble;
    }

    private void addItem() {
        String itemName = "";
        double price;
        int quantity;
        String namePrompt = "Enter the name of the item being added to the inventory: ";
        String pricePrompt = "Enter the cost of " + itemName + ": ";
        String quantityPrompt = "Enter the quantity of " + itemName + ": ";
        itemName = getUserString(namePrompt);
        price = getUserDouble(pricePrompt);
        quantity = getUserInt(quantityPrompt);
        controller.addItem(itemName, quantity, price);
    }




}

回答by oldrinb

As I stated in my comment, the problem is that you're closing System.ineach time you do something like this:

正如我在评论中所说,问题是每次你做这样的事情时你都在关闭System.in

Scanner scan = new Scanner(System.in);
...
scan.close();
Scanner scan = new Scanner(System.in);
...
scan.close();

Now, look at the specification of Scanner.nextLine

现在,看看规格 Scanner.nextLine

Throws:

  • NoSuchElementException- if no line was found
  • IllegalStateException- if this scanner is closed

抛出

  • NoSuchElementException- 如果没有找到行
  • IllegalStateException- 如果此扫描仪已关闭

Now, since the scanner itselfis not closed, an IllegalStateExceptionwill not be thrown. Instead, as you mentioned before, the other exception, "typically related to not finding a new line", -- NoSuchElementException-- is thrown.

现在,由于扫描仪本身并未关闭,IllegalStateException因此不会抛出an 。相反,正如您之前提到的,另一个异常“通常与找不到新行有关”, -- NoSuchElementException-- 被抛出。

Presuming this you're using JDK 7, you can see how this works by examining Scanner.throwFor:

假设您使用的是 JDK 7,您可以通过检查来了解它是如何工作的Scanner.throwFor

if ((sourceClosed) && (position == buf.limit()))
    throw new NoSuchElementException();

Since your exception is thrown, a value of 0is returned by getUserChar, which is then used in the runloop:

由于您的异常被抛出, 的值由0返回getUserChar,然后在run循环中使用:

do{
      userInput = mainMenu();
      if(isUserInputValid(userInput))
        ...
      else System.out.println("\nMainMenu");
    } while(!(wantToQuit));
do{
      userInput = mainMenu();
      if(isUserInputValid(userInput))
        ...
      else System.out.println("\nMainMenu");
    } while(!(wantToQuit));

Since the input is invalid, you're caught in a loop printing "\nMainMenu\n".

由于输入无效,您陷入了循环打印"\nMainMenu\n"

To correct the issue, try to use a single Scannerand don't close System.in;-)

要解决此问题,请尝试使用单个Scanner并且不要关闭System.in;-)

回答by Kumar Vivek Mitra

Please don't closethe Scanner.

不要关闭Scanner

scan.close();    // Don't do it.

Doing that is causing the problem.

这样做会导致问题。