繁体   English   中英

Java:两个扫描程序从同一输入文件中读取。 可行? 有用?

[英]Java: Two Scanners reading from the same input file. Doable? Useful?

我必须从输入文件中读取整数,这取决于它们之前出现的字符串是否是某个关键字“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扫描,二次扫描器仅用于整数,也可以向前移动主扫描器。 有没有办法阻止这种情况发生? 有什么方法可以让编译器将scan和loadscan视为单独的对象,尽管它们执行相同的任务?

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

假设myFile的内容是123 abc 下面的片段

    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

但是,我不知道你为什么要那样做。 为您的目的使用单个扫描仪会简单得多。 我在下面的片段中打电话给我的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();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM