I'm working on a java application that reads in data from a .txt
file, the scanner reads in each line of data from the .txt
file converts it into an object, then sends that object to a database I'm running on phpMyAdmin. However my scanner is skipping lines of data in my .txt
file. This results in input mismatch errors.
Heres the data in the .txt
file:
12
Sylvia Plath
The bell jar
6.99
The Bell Jar
10.99
1
Here's the method for reading in the data from the .txt
file
private static void readBookFile(Scanner kb, BookModel bmodel) //this method will allow the user to create a book, it then returns that book object
{
kb = new Scanner(System.in);
Print("Input File name:");
String inputFile = kb.nextLine();
File file = new File(inputFile + ".txt");
try {
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.next();
createBook(input, bmodel);
}
input.close();
} catch (FileNotFoundException ex) {
System.out.println("No such file exists");
}
}
And here is the method for converting that data to an object:
public static void createBook(Scanner enter, BookModel bModel) {
try {
String xx = enter.nextLine();
String an = enter.nextLine();
Print(an);
String ee = enter.nextLine();
String bn = enter.nextLine();
Print(bn);
Double cp = enter.nextDouble();
Print(cp);
Double sp = enter.nextDouble();
Print(sp);
int pc = enter.nextInt();
Book b = new Book(an, bn, cp, sp, pc);
bModel.addBook(b);
} catch (SQLException ex) {
}
}
I've tried adding an empty string to catch the skip but that still does not help. Here is the error I'm getting here, just to see where the data is being skipped:
=====================================================================
1. Read Books in from a text File.
2. Delete a Book
3. Add Product Category
4. Edit a Book.
5. View list of all current books.
6. Product menu
7. Exit
Please press select an option by using the numbers on your Keyboard
1
You Chose option: 1
Input File name:
in
Sylvia Plath
6.99
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at retailcompanydatabase.Classes.Menu.createBook(Menu.java:138)
at retailcompanydatabase.Classes.Menu.readBookFile(Menu.java:216)
at retailcompanydatabase.Classes.Menu.Menu(Menu.java:54)
at Main.Main.main(Main.java:12)
Here's the instance variables of the object I'm adding for further reference:
private int id;
private double costPrice;
private double sellPrice;
private String authorName;
private String bookName;
private int productCategoryID;
Any ideas on how I can try and fix this? I'd like to know how to fix it if possible instead of a workaround, if at all possible.