I am trying to use the Java Scanner class to read a text file all the way through and section each of the strings into the respected datatype such as a string "123" into long number = 123.
Here is my code:
public static void main(String[] args) throws NoSuchElementException, FileNotFoundException, IOException{
String filelocation = "file.txt";//this is for file path
ProductList p = new ProductList();
try {
File myObj = new File(filelocation);
Scanner src = new Scanner(myObj);
while (src.hasNextLine()) {
long id = Long.parseLong(src.nextLine());
String data = src.nextLine();
double op = Double.parseDouble(src.nextLine());
double cp = Double.parseDouble(src.nextLine());
String space = src.nextLine(); //without this line I get an error input ""
System.out.println(id +"\n"+ data +"\n"+ op +"\n"+ cp+"\n" + space);
}
src.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Here is the content in the text file:
121
Dining Table
129.99
119.99
1007
Leather Storage Ottoman
199.99
199.99
264
Gas-Powered Chainsaw
249.99
189.99
763
Protected Cruiser Takasago, 1898, 1/350, resin model kit
239.99
199.99
7465
Vacuum Cleaner, Green, 2252
99.99
89.99
354
Alienware 55 OLED Gaming Monitor - AW5520QF
4049.99
3039.99
Here is the output:
I do not understand why it is not printing the last item and how to take care of the error no line found. I understand you can throw an exception for illegals but I try that and still get the error.
At the end of file, an empty line is missing. In fact, it throws an exception when tries to read the last space at line String space = src.nextLine();
.
You can fix checking if the last space exists.
public static void main(String[] args) throws NoSuchElementException, FileNotFoundException, IOException{
String filelocation = "file.txt";//this is for file path
ProductList p = new ProductList();
try {
File myObj = new File(filelocation);
Scanner src = new Scanner(myObj);
while (src.hasNextLine()) {
long id = Long.parseLong(src.nextLine());
String data = src.nextLine();
double op = Double.parseDouble(src.nextLine());
double cp = Double.parseDouble(src.nextLine());
if (src.hasNextLine()) {
src.nextLine(); //read the space just if exists and it is not necessary to put it in a variable
}
System.out.println(id + "\n" + data + "\n" + op + "\n" + cp + "\n");
}
src.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}