gpt4 book ai didi

Java:两个扫描仪读取同一输入文件。可行吗?有用?

转载 作者:行者123 更新时间:2023-12-02 06:00:21 28 4
gpt4 key购买 nike

我必须根据出现在它们之前的字符串是否是某个关键字“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 对象同时从同一个 File 对象读取。推进一个不会推进另一个。

示例

假设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();
}
}
}

关于Java:两个扫描仪读取同一输入文件。可行吗?有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22723630/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com