0

プログラムで 3 つのテスト スコアを受け取り、それらの平均を出力する必要がありますが、スコアが -1 未満または 100 より大きい場合は、IllegalArgumentException をスローする必要があります。平均を出力することはできますが、-1 または 101 をテストすると、例外はスローされません。私は何を間違っていますか?

私は例外の学習に非常に慣れていないので、助けていただければ幸いです。

これが私のコードです:

import java.util.Scanner;
import java.io.*;

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

    int[]scores = new int [3];

    System.out.println("Score 1:");
    scores[0] = keyboard.nextInt();

    System.out.println("Score 2:");
    scores[1] = keyboard.nextInt();

    System.out.println("Score 3:");
    scores[2] = keyboard.nextInt();

    int totalScores = scores[0] + scores[1] + scores[2];
    int average = 0;

    if (scores[0] >= 0 && scores[0] <= 100 || 
        scores[1] >= 0 && scores[1] <= 100 ||
        scores[2] >= 0 && scores[2] <= 100)
    {
        try
        {
            average = totalScores / 3;
        }

        catch(IllegalArgumentException e) 
        {
            System.out.println("Numbers were too low or high.");
        }

        System.out.println("Average Score: " + average);
    }



} //end of public static void



} //end of TestScores
4

3 に答える 3

1

のブロックでtryアプリがスローする例外をキャッチできます。

のブロックではtry、 が表示されるだけでaverage = totalScores / 3;、例外はスローされません。そのため、投げられたものは何もキャッチしません。

この関数を使用して例外をスローできます - IllegalArgumentException

public static int getInputScore(Scanner keyboard) {
    int score = keyboard.nextInt();
    if (score < 0 || score >= 100) {
        throw new IllegalArgumentException(); 
    }
    return score;
}

mainコードで使用します。

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

    int[] scores = new int[3];

    System.out.println("Score 1:");
    try {
        scores[0] = getInputScore(keyboard);
    } catch (IllegalArgumentException e) {
        System.out.println("Numbers were too low or high.");
        return;
    }

    System.out.println("Score 2:");
    try {
        scores[1] = getInputScore(keyboard);
    } catch (IllegalArgumentException e) {
        System.out.println("Numbers were too low or high.");
        return;
    }

    System.out.println("Score 3:");
    try {
        scores[2] = getInputScore(keyboard);
    } catch (IllegalArgumentException e) {
        System.out.println("Numbers were too low or high.");
        return;
    }

    int totalScores = scores[0] + scores[1] + scores[2];
    int average = totalScores / 3;
    System.out.println("Average Score: " + average);
}
于 2014-02-21T04:15:15.980 に答える