Issue
I am trying to add an else if
to the code block inside my while loop below which tests if the LandingsData.txt
file is blank. If it is blank, then print "Starting with an empty system"
FileReader fr = null;
try {
fr = new FileReader("LandingsData.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
Scanner myFile = new Scanner(fr);
String line;
myFile.useDelimiter(",|\\n");
while (myFile.hasNext()) {
line = myFile.next();
if (line.equals("sl")) {
StrongLanding sl = new StrongLanding();
sl.setLandingId(Integer.parseInt(myFile.next()));
sl.setLandingDesc(myFile.next());
sl.setNumLandings(Integer.parseInt(myFile.next()));
sl.setCost(Double.parseDouble(myFile.next()));
landings.add(sl);
} else if (line.equals("ul")) {
UltimateLanding ul = new UltimateLanding();
ul.setLandingId(Integer.parseInt(myFile.next()));
ul.setLandingDesc(myFile.next());
ul.setNumLandings(Integer.parseInt(myFile.next()));
ul.setCost(Double.parseDouble(myFile.next()));
landings.add(ul);
} else if (fr.length() == 0) {
System.out.println("Starting with an empty system");
}
}
I've tried a few different ways with this using fr.length()
or fr.count()
but I seem to be receiving the error The method length() is undefined for the type FileReader
I've also tried a few different spots outside of the while loop as I thought this might be the issue, but no luck
TIA
Solution
Scanner myFile = new Scanner(fr);
String line;
myFile.useDelimiter(",|\\n");
if (!myFile.hasNext()){
System.out.println("Starting with an empty system");
} else {
while (myFile.hasNext()) {
line = myFile.next();
if (line.equals("sl")) {
// Do stuff
} else if (line.equals("ul")) {
// Do stuff
}
}
}
Call hasNext()
once before reading the file to see if the file is empty.
Answered By - okzoomer
Answer Checked By - Marilyn (JavaFixing Volunteer)