【问题标题】:Using Scanner - at java.util.Scanner.next(Unknown Source) java.util.NoSuchElementException使用扫描仪 - 在 java.util.Scanner.next(Unknown Source) java.util.NoSuchElementException
【发布时间】:2013-02-08 06:46:19
【问题描述】:

我的完整代码已粘贴here。以下是与我的问题相关的两种方法。

private static boolean playGameAgain()
{
        char playAgain = 'y';
        Scanner input = new Scanner(System.in);
        while(playAgain != 'n')
        {
                System.out.println("Go again?(y/n)");
/// PROBLEM HERE....  Somehow, it will NOT wait for INPUT. It just throws an error
                playAgain = input.next().charAt(0);
        }
        input.close();
        return (playAgain != 'y')?false:true;
}

// [Trimmed]

public static void initialize(ArrayList<String> names, ArrayList<Integer> scores)
{
        Scanner input = new Scanner(System.in);
        for (int i = 1; i <= 5; i++)
        {
                System.out.println("Enter the name for score #" + i + ":");
                names.add(input.nextLine());
                System.out.println();
                System.out.println("Enter the score for score #" + i + ":");
                while(!input.hasNextInt())
                {
                        //input.nextLine();
                        System.out.println("Please input a valid integer value for the score for #" + i + ":");        
                        if(!input.hasNextInt())
                                 input.nextLine();
                }
                scores.add(input.nextInt());
                input.nextLine();
        }
        input.close();
}

我已经尝试了很多组合如何阅读一个字符。这曾经有效,我可以使用以下方法读取一个字符:

Scanner input = new Scanner(System.in);
char temp = input.next().charAt(0);

但是,不知何故,在我编写的这个程序中,它不起作用。

这是一个程序,它将读取 5 个用户名(字符串)和 5 个分数(整数)并将它们放入 2 个数组中。它将按降序对数组进行排序,然后将它们打印出来。所以,我唯一的问题是问他们是否想再玩一次并输入一些字符来看看他们是否想再玩一次(y/n)?

如果可以,请提供帮助。我尝试了很多组合:if (input.hasNext()),但无济于事。

【问题讨论】:

  • input.next().charAt(0) 会要求用户输入换行符,您考虑正确吗?
  • 我已经编辑了您的问题,以包括我认为对问题至关重要的部分。 请检查是否要包含更多内容。您可以查看revision 了解更改内容。

标签: java system.in


【解决方案1】:

您没有将playAgain 设置为playGameAgain() 中的“y”以外的值。你这里有一个错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多