【解決方法】特定の配列から特定の値を返す方法


このプログラムでは、銅メダリストのスコアを見つけています。 標準入力から一連のスペースで区切られた 10,000 以下の負でない整数を読み取るプログラムを作成しています。 私のプログラムは、銅メダリストのスコアに対応する整数値を標準出力に書き出すことです。 複数の競技者が同じスコアで同点になる可能性がありますが、金、銀、銅のメダリストは 1 人だけです。 同点の場合は、自分のターンにかかる累積時間が最も短い競技者が勝ちます。 あなたのプログラムは、銅メダリストのスコアを報告するだけで済みます。

• プログラムは、各整数がゼロ (0) から 1 万 (10,000) までの標準整数から読み取ってから、銅メダリストのスコアを表す単一の整数を標準出力に書き込む必要があります。

• プログラムを実行しようとすると、次のように実行されます。

javac Program.java

エコー 27 3 9 3 6 27 10 15 8 | Java プログラム

15

私が試したこと:

これは私が現在持っているコードですが、3 位ではなく常に -1 を返します。

Java
<pre>import java.util.Scanner;

public class Program {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int n = args.length;
        int[] scores = new int[n];

        // read in scores
        for (int i = 0; i < n; i++) {
            scores[i] = input.nextInt();
        }

        // find the third highest score
        int max1 = -1, max2 = -1, max3 = -1;
        for (int i = 0; i < n; i++) {
            if (scores[i] > max1) {
                max3 = max2;
                max2 = max1;
                max1 = scores[i];
            } else if (scores[i] > max2 && scores[i] < max1) {
                max3 = max2;
                max2 = scores[i];
            } else if (scores[i] > max3 && scores[i] < max2) {
                max3 = scores[i];
            }
        }

        // output the third highest score
        System.out.println(max3);
    }
}

解決策 1

これを試して:

Java
import java.util.Scanner;

public class Program {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int n = 0;
        int score;

        // read in scores
        int max1 = -1, max2 = -1, max3 = -1;
        while (input.hasNext()) {
            score = input.nextInt();

            if (score > max1) {
                max1 = score;
            } else if (score > max2) {
                max2 = score;
            } else if (score > max3) {
                max3 = score;
            }
        }

        // output all scores
        System.out.println(max1);
        System.out.println(max2);
        System.out.println(max3);
    }
}

コメント

タイトルとURLをコピーしました