【问题标题】:Java Scanner.nextLine() not waiting for inputJava Scanner.nextLine() 不等待输入
【发布时间】:2012-08-25 18:58:10
【问题描述】:

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

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

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;
}

由于 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);
    }




}

【问题讨论】:

  • 每次关闭Scanners 时,您都会关闭System.in。无论如何,您应该只需要一个Scanner
  • 哈哈...我可以踢自己的脸。我的最后一个程序没有关闭它们,所以它们可以工作,但是这个新版本的 Eclipse 每次都告诉我要关闭它们。我想我会尝试重做,谢谢。

标签: java


【解决方案1】:

正如我在my comment 中所说,问题在于每次执行此类操作时都会关闭System.in

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

现在,看看Scanner.nextLine的规范

投掷

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

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

假设您使用的是 JDK 7,您可以通过检查 Scanner.throwFor 来了解其工作原理:

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

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

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

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

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

【讨论】:

  • 哇,我期待一两行。不错的答案! 1+
  • 感谢您的解释。哈哈,当我调试它时,我不明白为什么它总是跳过所有内容,但现在这很有意义。
  • 我的天啊,我已经研究了一段时间,是的,我使用了不止一个扫描仪并关闭了其中一个,我无法绕开它。感谢您的评论。
【解决方案2】:

不要关闭Scanner

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

这样做会导致问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多