【发布时间】:2016-03-28 23:59:00
【问题描述】:
我创建了三个文本文件,inputt.txt、outputt.txt 和 errorr.txt。 Inputt.txt 用于输入,outputt.txt 应该打印 inputt.txt 中所有有效整数的数字,errorr.txt 打印输入文本文件中的所有错误。我在迭代时遇到了麻烦。 System.out.println 可以很好地打印 inputt.txt 中的所有数字;但是,当我尝试将所有数字打印到 outputt.txt 中时,它只打印第一行数字。这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Lab5_Exceptions_Redo extends Exception {
public static void main(String[] args) throws FileNotFoundException {
String file = "inputt.txt";
String file1 = "outputt.txt";
String file2 = "errorr.txt";
PrintWriter errorr = new PrintWriter(file2);
PrintStream ps = new PrintStream(file2);
PrintWriter outputt = new PrintWriter(file1);
Scanner scan = new Scanner(new File(file));
while (scan.hasNext()) {
try {
String number = scan.nextLine();
int num = Integer.parseInt(number);
System.out.println(num);
outputt.println(num);
} catch (InputMismatchException e) {
errorr.println("There was an input mismatch error.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (NoSuchElementException e) {
errorr.println("There is no such element.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (UnsupportedOperationException e) {
errorr.println("An unsupported operation occured.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (NumberFormatException e) {
errorr.println("Number Format Exception.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
}
errorr.close();
outputt.close();
}
scan.close();
}
}
【问题讨论】:
-
您正在循环中关闭
outputt。把它移到外面去修理。投票结束是一个错字。 -
我不能在外面关闭它,因为里面是我声明变量的地方,我不能把变量移到外面,因为它们必须在我的 try 语句中。
标签: java while-loop iteration text-files