The problem is with your logic flow of the program. Here's what the code is doing:
Read in one number, store in both lowest
and lowest2
.
Go through loop to read in more numbers
2a. If the number is positive, check against lowest
.
2a1. If the read in value is lower than lowest
, change lowest
's value to the read in value.
2a2. Otherwise, if the read in value is lower than lowest2
, change lowest2
's value to the read in value. Only do this if lowest
was not changed.
2b. If the read in value is -1, end the loop.
2c. If the read in value is negative but not -1, continue but don't add the number to lowest
or lowest2
.
Print out the values for lowest
and lowest2
.
If you see the error, it's in 2a2. This is linked to the fact that your setup before the while
loop is formatted as you did: you made both lowest
and lowest2
that first value.
This code would normally run correctly, except for one instance: what if that first value were to be the smallest positive value you entered, with all other values greater than it? lowest2 would be set to that value, and you're checking to see if any other values are smaller than it (which they're not, because they're all going to be greater than it).
Tips for when you're coding:
1) Attempt to develop a logical thinking mentality. Think through how you want to create algorithms for your program. Make sure you don't run into any situations where your program does not run the way you want it to, like in this case (this is called a logic error).
2) Run through your programs by hand when you're finished coding, or after you've run it and got an error. Step through every line of your code, and try to see where and why your code isn't working the way you want it to. Or have someone else see, like a fellow programmer. Sometimes, even the best eyes do not catch their own mistakes.
EDIT:
There are various ways to solve this particular problem. One way is to do what Seeker and Rick did:
1) Set both values to the largest possible Integer value, and thus all values entered will be lower than the first values.
2) Ask for the first two inputs at the beginning before the loop, and check them against each other to set the first two lowest values.
However, I believe there are certain things to watch out for when you're doing something like this. These should all be outlined before you code, of course.
1) What if the user is entering only one or zero valid values? Seeker's method wouldn't work, unless he checks that the first/second value is negative/-1. Rick's method wouldn't work either because at least one of the lowest/lowest2 values would still be that max Integer value.
2) What if there were no positive values entered before the -1? This is similar to number 1, and your ints
would be null.
You can certainly use Seeker's and Rick's algorithms, but you should check for these conditions if you use them.