为什么扫描仪不工作

时间:2013-02-07 02:12:22

标签: java

我正在尝试阅读此格式的输入

4 4
* . . .
. . . .
. * . .
. . . .
4 4
* * . .
. . . .
. . . .
. . * .

我能够读取前两个数字,当我尝试读取符号时,我得到一个异常。我可以使用BufferedReader读取每一行并解析输入,但为什么我不能用扫描仪做这个?

这是我的代码

        public static void main(String[] args) {
                Scanner in = new Scanner(System.in);
                while (in.hasNextLine()) {
                    Scanner s = new Scanner(in.nextLine());
                    if (!s.hasNextLine())
                        break;

                    int x = s.nextInt(); // 4
                    int y = s.nextInt(); // 4
                    for (int i = 0; i <= x - 1; i++) {
                        for (int j = 0; j <= y - 1; j++) {
                            System.out.println(s.hasNext()); // false
                            String symbol = s.next(); //NoSuchElementException WHY?
                        }
                    }
                }
            }
        }

2 个答案:

答案 0 :(得分:2)

当没有任何数字时,你不应该尝试读取数字。

你的循环,伪代码,看起来像

While there is a line available:
    s = NextLine()
    x = FirstInt(s)
    y = SecondInt(s)
    // Some other stuff

当您分配到xy时,除第一行外没有可用的号码,因此您的应用程序崩溃。

与问题相匹配的更好的解决方案是

Scanner in = new Scanner(System.in);
if (!in.hasNextInt()) exitAndPrintError();
int rows = in.nextInt();
if (!in.hasNextInt()) exitAndPrintError();
int cols = in.nextInt();
for (int r = 0; r < rows; r++) {
    for (int c = 0; c < cols; c++) {
        if (!in.hasNext()) exitAndPrintError();
        process(in.next());
    }
}

此解决方案确实没有检查错误,将所有错误报告留给您必须编写的某些exitAndPrintError函数。

作为旁注:如果您尝试s.hasNext()并且它返回false,那么如果s.next() 没有抛出异常,您会感到惊讶。这就是hasNext* Scanner方法可用于s的原因 - 它们让您有机会知道何时到达输入结束,而不是尝试读取任何可用的输入。


我会将其作为练习来更新此代码以在单个文件中处理多组数据,但这并不困难。您发布的代码中的关键错误是,如果您仅使用in中的一行创建扫描程序s,则在该单行内找不到多行结构{{1正在处理。

答案 1 :(得分:1)

总体设计问题可以解决,我会回答你的问题。

你得到NoSuchElementException因为,猜猜是什么,s没有更多元素。 s.hasNext()的输出返回false会变得更加明显。

原因很简单。您为s分配了一行in

要修复整个程序,您需要使用的只是一个扫描程序,而不是它的多个实例。

相关问题