我创建了三个文本文件,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();
}
}
答案 0 :(得分:0)
PrintWriter流变量errorr应该移出for循环。请尝试以下版本的代码。
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();
}
}