I have a file that has the following data:
19387,73616,11/10/2021,7268,8271
81716,16381,11/10/2021,2736,3715,7362,837
75464,27315,11/10/2021,,3545,7645,460
- The format is: id1, id2, yyyy/mm/dd, price, id3.
- There can be multiple id3s (some lines have more data).
The data types are: int, int, string, float, arraylist integer. So here, I only want to read id3 as an integer arraylist
My code so far:
Public static void main(String[] args){
//variables
int id1;
int id2;
String date;
float price;
ArrayList<Integer> id3List = new ArrayList<>();
//check if file exists
try {
//get file
File myFile = new File (“fileName.txt“);
//pass file object to create scanner object
Scanner inputFile = new Scanner ("myFile").useDelimiter(",|\\r|\\n");
//read lines from file and store into respective variables
try {
While (inputFile.hasNextInt){
id1 = inputFile.nextInt();
id2 = inputFile.nextInt();
date = inputFile.next();
price = inputFile.nextFloat();
id3.add(inputFile.nextInt());
inputFile.nextLine(); //consume a line
} catch(InputMismatchException e){
System.out.println("Bad data in file.");
}
System.out.println(id3);
inputFile.close(); //close file
} catch(FileNotFoundException e) {
System.out.println("The file was not found.");
}
}
The result i get only displays the first id3 and ignores the rest:
[8271, 3715, 7645]
Note: I will only be using a scanner for this, not buffered reader.