import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class Greencrud {
public static void main(String[] args) {
Scanner inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new FileInputStream("greencrud.txt"));
outputStream = new PrintWriter(new FileOutputStream("crudout.txt"));
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
while (inputStream.hasNextLine()) {
int a = 0, b = 1;
int f = 0;
int total = 0;
int times = 0;
int population = inputStream.nextInt();
int days = inputStream.nextInt();
int next = days / 5;
while (times <= next - 2) {
times++;
f = a + b;
a = Math.max(a, b);
b = f;
}
total = f * population;
outputStream.println("A green crud population starts out as " + population + " pounds of crud");
outputStream.println("It grows to " + total + " pounds of crud in " + days + " days");
outputStream.close();
inputStream.close();
}
}
}
输入文件greencrud.txt
:
12 10 4 30 28 18 7 13 17 10 9 35 10 20
当我调用该方法时,int population = inputStream.nextInt();
出现问题。它提醒我java.lang.IllegalStateException: Scanner closed
。另外,我只能将greencrud.txt
中的第一行数据输出到crudout.txt
。如何解决问题,以便可以在crudout.txt
上打印所有日期?
答案 0 :(得分:0)
您正在关闭循环内的流
outputStream.close();
inputStream.close();
把它带出循环。
答案 1 :(得分:0)
将inputStream.close();
行放在while
循环之外。
因为扫描仪已经关闭,下一次迭代inputStream.hasNextLine()
将产生IllegalStateException
。
与outputStream.close();
相同。