如何将 20k 行的 .txt 文件转换为对象?

How can I convert 20k line of .txt file in to Object?

我有 20k 行的 .txt 文件。我的问题是我收到此错误和消息。我创建了四个 类。我将流程扩展到转换器中。然后我想将名称、价格、数量和总计从我的 records.txt.

转换为对象
Exception in thread "main" java.util.InputMismatchException
        at java.base/java.util.Scanner.throwFor(Scanner.java:943)
        at java.base/java.util.Scanner.next(Scanner.java:1598)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2263)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2217)
        at InvoiceConverter.ConvertStringToObject(InvoiceConverter.java:18)
        at MyMainClass.main(MyMainClass.java:7)

这是我的 .txt 文件的示例

Banana
125.50
3
376.50

这是我的 Converter.class

public class Converter extends Process {
    Converter(String name, double price, int quantity, double total) {
        super(name, price, quantity, total);
    }
    public Converter() {

    }
    public void ConvertStringToObject() {
        String fileName = "records.txt";
        List<Process> invoice = new ArrayList<>();
        try (Scanner sc = new Scanner(new File("records.txt"))){
            int count = sc.nextInt();
            for (int i = 0; i < count; i++) {
                String name = sc.nextLine();
                double price = sc.nextDouble();
                int quantity = sc.nextInt();
                double total = sc.nextDouble();
                invoice.add(new Process(name, price, quantity,total));
            }
        } catch (IOException e) {
            System.out.println("Error Occurred");
            e.printStackTrace();
        }
    }
}

这是我的 Process.class

public class Process {
    String name;
    double price;
    int quantity;
    double total;

    Process(String name, double price, int quantity, double total) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
        this.total = total;
    }
    public Process() {

    }
}

这是我的 records.txt enter image description here

我该如何解决这个问题?

您需要在阅读数字后消耗换行符。读号后需要拨打sc.nextLine()

正如 Andy 在评论中提到的,文件的第一行应该包含 Process 个对象。所以你的文件需要以包含数字的单行开头,之后你还需要使用换行符。

您可以这样使用文件:

int count = Integer.parseInt(sc.nextLine()
for (int i = 0; i < count; i++) {
  String name = sc.nextLine();
  double price = Double.parseDouble(sc.nextLine());
  int quantity = Integer.parseInt(sc.nextLine());
  double total = Double.parseDouble(sc.nextLine());
  invoice.add(new Process(name, price, quantity,total));
}