Reputation: 55
I'm suppose to catch the NoSuchElementException if a field is missing while reading a file. If there is a field missing, I just need to skip to the next line of the file. My question is, where do I implement my try/catch code to do this? Here is the codes:
String petType;
int lineNumber = 0;
while(input.hasNext()) {
petType = input.next();
lineNumber++;
//I'm thinking of doing it for every if(input.hasNext()) but that would be too messy to read.
if(petType.equals("BIRD")) {
if(input.hasNext())
String name = input.next();
if(input.hasNext())
String owner = input.next();
if(input.hasNextDouble())
double weight = input.nextDouble();
if(input.hasNextBoolean())
boolean clipped = input.nextBoolean();
Bird x = new Bird(name,owner,weight,clipped);
object.addPet(x);
}
}
Upvotes: 0
Views: 1997
Reputation: 22692
Just get rid of all your hasNextXXX() calls and let nextXXX() throw the exception for you.
String petType;
int lineNumber = 0;
while (input.hasNext()) {
lineNumber++;
try {
petType = input.next();
if (petType.equals("BIRD")) {
String name = input.next();
String owner = input.next();
double weight = input.nextDouble();
boolean clipped = input.nextBoolean();
Bird x = new Bird(name, owner, weight, clipped);
object.addPet(x);
}
}
catch (NoSuchElementException nse) {
System.out.println("something is missing in line " + lineNumber);
}
}
That being said, I'd argue that it's better to keep all your hasNextXXX calls and to break out of the current iteration (using continue) if any of them return false. This will achieve the same affect as catching the exception, but without the unneccessary overhead of using a try/catch.
My guess is your teacher just wants you to learn about Exceptions, though...
Upvotes: 2
Reputation: 793
If a field is missing - your input.hasNext()/input.hasNextDouble/input.hasNextBoolean will return false... Do you really need to catch an exception - since you are checking field existence anyway?
You can just skip to next line if any of the if conditions fail.
Upvotes: 0