我試着從我的input.txt文件中解析字符串,但是我得到每次拋出的NumberFormatException異常。我已經添加了迄今爲止所有的代碼。 我也嘗試過.trim。我對Java中的文本文件非常陌生;因此,我不知道這裏有什麼問題。但是,任何幫助將不勝感激。如何在JAVA中解析來自文本文件的輸入?
import java.io.File;
import java.io.FileNotFoundException;
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);
PrintWriter inputt = new PrintWriter(file);
inputt.println(15951);
// int whatever = Integer.parseInt(file);
// System.out.print(whatever);
inputt.close();
Scanner scan = new Scanner(file);
String number = scan.nextLine();
int num = Integer.parseInt(number.trim());
System.out.printf("%d", num);
PrintWriter outputt = new PrintWriter(file1);
outputt.println(num);
outputt.close();
// inputt.close();
scan.close();
// System.out.printf("%d", num);
try {
} catch (InputMismatchException e) {
errorr.println("There was an input mismatch error.");
} catch (NoSuchElementException e) {
errorr.println("There is no such element.");
} catch (UnsupportedOperationException e) {
errorr.println("An unsupported operation occured.");
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
errorr.close();
}
}
你嘗試調試的問題?當你嘗試打印'num'時,你看到了什麼? – TheLostMind