【问题标题】:Java: Two Scanners reading from the same input file. Doable? Useful?Java:两个扫描仪从同一个输入文件中读取。可行吗?有用?
【发布时间】:2014-05-08 13:15:21
【问题描述】:

我必须根据出现在它们之前的字符串是否是某个关键字“load”来从输入文件中读取整数。没有键号告诉将要输入多少个数字。这些数字必须保存到数组中。为了避免为每个扫描的附加数字创建和更新一个新数组,我想使用第二个扫描仪首先找到整数的数量,然后让第一个扫描仪扫描多次,然后再返回测试字符串.我的代码:

public static void main(String[] args) throws FileNotFoundException{
    File fileName = new File("heapops.txt");
    Scanner scanner = new Scanner(fileName);
    Scanner loadScan = new Scanner(fileName);
    String nextInput;
    int i = 0, j = 0;
    while(scanner.hasNextLine())
    {
        nextInput = scanner.next();
        System.out.println(nextInput);
        if(nextInput.equals("load"))
        {
            loadScan = scanner;

            nextInput = loadScan.next();
            while(isInteger(nextInput)){
                i++;
                nextInput = loadScan.next();
            }

            int heap[] = new int[i];
            for(j = 0; j < i; j++){
                nextInput = scanner.next();
                System.out.println(nextInput);
                heap[j] = Integer.parseInt(nextInput);
                System.out.print(" " + heap[j]);
            }
        }




    }

    scanner.close();
}

我的问题似乎是通过 loadscan 进行扫描,仅用于整数的辅助扫描仪也会向前移动主扫描仪。有没有办法阻止这种情况发生?有什么方法可以让编译器将scanner 和loadscan 视为单独的对象,尽管它们执行相同的任务?

【问题讨论】:

  • 所有数字都在一行吗?如果是这样,那么我会为需要它的每一行使用文件扫描仪和扫描仪。但请记住在不再需要时丢弃所有扫描仪。
  • 请注意,在上面的代码中,您创建了两个 Scanner 对象,但只使用其中一个,因为您调用了 loadScan = scanner;,它将相同的 Scanner 对象分配给两个 Scanner 变量。
  • 另外,为什么不将您的号码保存到 ArrayList&lt;Integer&gt; 而不是数组?那么你就不用太担心声明数组的正确大小了。
  • 气垫船,你知道有什么方法可以让两个扫描仪指向文件的同一区域而不成为同一个对象吗?
  • 请先回答我的问题。让我们不要以此为基础制造 XY 问题。还请展示您阅读过的典型文本文件,或者可能是其中的小版本。

标签: java string io integer java.util.scanner


【解决方案1】:

您当然可以同时从同一个 File 对象读取两个 Scanner 对象。推进一个不会推进另一个。

示例

假设myFile的内容是123 abc。下面的sn-p

    File file = new File("myFile");
    Scanner strFin = new Scanner(file);
    Scanner numFin = new Scanner(file);
    System.out.println(numFin.nextInt());
    System.out.println(strFin.next());

...打印以下输出...

123
123

但是,我不知道您为什么要这样做。为您的目的使用单个 Scanner 会简单得多。我在下面的 sn-p 中调用了我的fin

String next;
ArrayList<Integer> readIntegers = new ArrayList<>();
while (fin.hasNext()) {
    next = fin.next();
    while (next.equals("load") {
        next = fin.next();
        while (isInteger(next)) {
            readIntegers.Add(Integer.parseInt(next));
            next = fin.next();
        }
    }
}

【讨论】:

  • 您确定最后一个 while 循环应该是示例代码中的 while 循环吗? next 永远不会在正文中编辑,因此它要么循环无穷大,要么根本不循环
  • @ferrybig 这应该是if。感谢您了解这一点。
  • @ferrybig 哎呀,不,我让事情变得更糟了。在“load”关键字之后可以有任意数量的数字。我认为while 应该在那里,但我每次都忘记推进扫描仪。看到这个问题已经一年多了,请多多包涵。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
相关资源
最近更新 更多