扫描仪流为什么关闭

时间:2015-11-05 05:24:31

标签: java file-io

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上打印所有日期?

2 个答案:

答案 0 :(得分:0)

您正在关闭循环内的流

outputStream.close();
inputStream.close();

把它带出循环。

答案 1 :(得分:0)

inputStream.close();行放在while循环之外。

因为扫描仪已经关闭,下一次迭代inputStream.hasNextLine()将产生IllegalStateException

outputStream.close();相同。