stringjava:两个扫描器从同一个输入文件读取数据。可行吗?有用的
我必须根据前面出现的字符串是否是某个关键字“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视为单独的对象,尽管它们执行相同的任务
# 1 楼答案
您可能会同时从同一文件对象读取两个扫描仪对象。推进一个不会推进另一个
示例
假设
myFile
的内容是123 abc
。下面的片段。。。打印以下输出
然而,我不知道你为什么要这么做。为您的目的使用单个扫描仪会简单得多。我在下面的代码片段中调用了我的
fin