【发布时间】: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<Integer>而不是数组?那么你就不用太担心声明数组的正确大小了。 -
气垫船,你知道有什么方法可以让两个扫描仪指向文件的同一区域而不成为同一个对象吗?
-
请先回答我的问题。让我们不要以此为基础制造 XY 问题。还请展示您阅读过的典型文本文件,或者可能是其中的小版本。
标签: java string io integer java.util.scanner