java - 为什么扫描仪不工作

标签 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?
                        }
                    }
                }
            }
        }

最佳答案

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

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

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 上可用 - 它们让您有机会知道何时到达输入末尾,而不是尝试读取更多输入比可用的。

<小时/>

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

关于java - 为什么扫描仪不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14742408/

相关文章:

java - 自动启动 JBoss 服务 (MBean)

java - 我应该使用哪个 .JAR 来嵌入 Jetty?

Java - 是否可以将客户端发送到另一台服务器?

java - 如何从 Java 将数据库连接传递给 Kettle 作业

具有数据库可执行文件的 JavaFx 应用程序

java - 如何使用 Java 中的 Spliterator 测试并行处理的性能

java - HTTP 状态 500 - javax.el.PropertyNotFoundException : Property 'first_name' not found on type java. lang.String

java - 检查代码是否有潜在的 Java 7/8 改进

java - 在电子邮件中发送交互式表单

java - 当一个类从抽象类扩展时,如何访问它的私有(private)变量?