【问题标题】:how to use two scanners on one method如何在一种方法中使用两个扫描仪
【发布时间】:2019-03-25 05:44:18
【问题描述】:

今天早些时候我问how to re-try/catch input mismatch exception without getting caught by infinite loop

但这是两个过程,首先游戏会询问用户网格的大小,然后在启动后它会要求他设置一个标志或跨过一个单元格(如果我的游戏将是否则它会打印出周围地雷的数量),但我得到了一些奇怪的错误 代码:

int gridSize = 0;
    try (Scanner scanner = new Scanner(System.in)) {
        System.out.println("how much the size of the grid do you want");
        while (!scanner.hasNextInt()) {
            System.err.println("Try again, this time with a proper int");
            scanner.next();
        }
        gridSize = scanner.nextInt();
    }
    MinesWeeper grid = new MinesWeeper(gridSize);
    grid.printOut();

    int choice = 0;
    try (Scanner scanner = new Scanner(System.in)) {
        System.out.println("1-to step over a cell\n2-to set a flag on the cell");
        while (!scanner.hasNextInt()) {
            System.err.println("Try again, this time with a proper int");
            scanner.next();
        }
        choice = scanner.nextInt();
    }

    boolean Continue = true;
    while (Continue) {
        switch (choice) {
            case 1:
                if (grid.chooseCell(1)) {
                    Continue = false;
                }
                break;
            case 2:
                grid.chooseCell(2);
                break;
        }
    }

错误:

how much the size of the grid do you want 3 A B C
Try again, this time with a proper int 1 * * * Exception in thread "main" java.util.NoSuchElementException 2 * * * at java.util.Scanner.throwFor(Scanner.java:862) 3 * * * 1-to step over a cell at java.util.Scanner.next(Scanner.java:1371) at Array.Main.main(MinesWeeper.java:188) 2-to set a flag on the cell

奇怪的是它在我的打印语句之间打印异常消息(网格是一个语句,指令也是一个)

当我进行搜索时,我发现我不能在同一地点使用两台扫描仪, 但是如果它们在尝试使用资源时初始化,我该如何分离它们

【问题讨论】:

    标签: java try-catch java.util.scanner try-with-resources


    【解决方案1】:

    这个:

    try (Scanner scanner = new Scanner(System.in)) {
      // ...
    }
    

    是一个 try-with-resources 块。当块执行完毕后,它会调用scanner.close()

    对于您的用例,问题在于扫描程序反过来调用System.in.close()。一旦流被关闭,您将无法再次读取它,因此当您随后尝试创建另一个从 System.in 读取的 Scanner 时会出现异常。

    对您的代码最简单的修复是合并两个 try-with-resources 块,并重用同一个 Scanner,这样您就不会在两者之间关闭它。无论如何,没有充分的理由拥有两个单独的扫描仪。

    但实际上,您根本不应该使用 try-with-resources。

    一般规则是不要关闭你不拥有的流,这大致翻译为不要关闭你没有打开的流,给定Java没有“所有权”的概念。 System.in 不是你打开的,是 JVM 打开的。

    您不知道您的程序中还有什么依赖于它继续打开。如果你关闭了这样的流,你会为流的未来读者弄乱流的状态。

    现在,您可能认为需要使用 twr,否则您的 IDE 会在 Scanner 上标记资源泄漏警告。通常,您可能想要关闭扫描仪;在这种特定情况下,您不需要。忽略(或禁止)该警告,如果这就是您使用 twr 的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 2010-09-11
      相关资源
      最近更新 更多