I have 20k lines of .txt file. My problem is I got this error and message. I created four classes. I extend the Process into Converter. Then I want to convert the name, price, quantity, and total into Objects from my 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)
Here's the example of my .txt file
Banana
125.50
3
376.50
Here's my 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();
}
}
}
Here's my 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() {
}
}
Here's my records.txt enter image description here
How can I solve this problem?
CodePudding user response:
You need to consume linebreaks after reading numbers. You need to call sc.nextLine()
after reading a number.
As Andy mentioned in the comments, the file is supposed to have the number of Process
objects in the first line. So your file needs to start with a single line containing a number, and you also need to consume the linebreak after that.
You can consume the file like this:
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));
}