Reputation: 49
Should run a program that prints the largest, and second largest, but having problems getting the second value. Think my Boolean expression is wrong cause I keep getting 0 as tempSecond. Can you help?
/*
* File: AddExamIntegers.java
* --------------------
* This program takes a list of integers until Sentinel,
* then prints the largest and second largest.
*/
import acm.program.*;
public class FindLargest extends ConsoleProgram {
public void run() {
println("This program takes a list of integers and then lists the largest and second largest");
println("");
println("Enter positive numbers using " + SENTINEL);
println("to signal the end of the list");
int tempHigh = 0;
int tempSecond = 0;
while (true) {
int value = readInt(": ");
if (value == SENTINEL) break;
if (tempHigh < value) {
tempHigh = value;
}
if ((tempSecond < value) && (tempSecond > tempHigh)) {
tempSecond = value;
}
}
println("The largest value is " + tempHigh);
println("The second largest value is " + tempSecond);
}
private static final int SENTINEL = 0;
}
Upvotes: 0
Views: 811
Reputation: 16035
The second part of your latter if will never be true: tempSecond > tempHigh
Instead, do this:
if(tempHigh < value)
{
tempHigh = value;
}
else if(tempSecond < value)
{
tempSecond = value;
}
Upvotes: 3