Reputation:
I'm working on a program that is supposed to read numbers (double) in from a file and perform some calculations on them (creating octagon objects). However, we are supposed to end the program when a negative number is read in, and I'm not sure how to do this?
The file that is being used looks like this:
5.0
7.5
3.26
0.0
-1.0
I am using a while loop to read in the file and assign the values to variables, so would I just need to add something to my while loop to end if the number is negative? Something like:
while(fin.hasNext()) {
double side = fin.nextDouble();
if(side < 0)
//do whatever I need to do to end the program
}
Or am I totally wrong in that thinking?
Thanks in advance for any input.
Upvotes: 1
Views: 607
Reputation: 111
It would be as simple as doing
while(fin.nextDouble()) {
double d = fin.nextDouble();
if (d < 0) {
break;
}
...
}
Another approach to doing this would be doing
double d;
while(fin.hasNextDouble() && (d = fin.nextDouble()) >= 0) {
...
}
Upvotes: 1
Reputation: 635
This doesn't quite work, because fin.hasNext()
only returns whether or not the next line is EOF (aka there is no more text), not the contents themselves. You will need to check for a negative value inside the loop. This is done by calling nextDouble()
and comparing it with 0, and then breaking if it isn't positive. All of this is assuming that you are using Java's Scanner class.
The code would be:
while (fin.hasNextDouble()) {
double num = fin.nextDouble();
if (num < 0.0) break;
// do your stuff
Upvotes: 1