您如何解析 JAVA 中文本文件的输入?

How do you parse input from a text file in JAVA?

我试图从我的 input.txt 文件中解析字符串,但每次都会抛出 NumberFormatException。到目前为止,我已经添加了所有代码。 我也试过 .trim 。我对 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();

    }
}

在执行 nextLine() 时,您必须在输入的同时获取空格。使用 trim() 函数去除任何空格。

int num = Integer.parseInt(number.trim());

或者,您可以尝试使用 nextInt() 而不是 nextLine()

这是 parseInt() 的 JAVA 文档:

Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.

你做错了。在 Scanner 构造函数中,您应该传递 File 对象而不是 String 对象。由于您正在传递字符串 "inputt.txt" 它试图解析此字符串,因此您得到了 NFE。 试试这个

Scanner scan = new Scanner(new File(file));