0

最大値と 2 番目に大きい値を出力するプログラムを実行する必要がありますが、2 番目の値の取得に問題があります。tempSecond として 0 を取得し続けるため、ブール式が間違っていると思います。手伝ってくれますか?

/*
 * 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;

}
4

1 に答える 1

3

後者の if の 2 番目の部分が真になることはありません。tempSecond > tempHigh

代わりに、次のようにします。

        if(tempHigh < value)
        {
            tempHigh = value;
        }
        else if(tempSecond < value)
        {
            tempSecond = value;
        }
于 2012-08-05T09:38:55.453 に答える