Is dit de juiste manier om een ​​IllegalArgumentException te gebruiken?

Ik probeer aan een Java-opdracht te werken. Dit is wat het vraagt:

Schrijf een klasse met de naam TestScores. De klassenconstructor moet een array van de testscores als argument accepteren. De klasse moet een methode hebben die het gemiddelde van de testscores retourneert. Als een testscore in de array negatief of groter is dan 100, moet de klasse een IllegalArgumentException geven. Tonen. Ik heb een bestand nodig met de naam TestScores en TestScoresDemo.

Dit is wat ik tot nu toe heb. Ik weet dat een deel ervan niet klopt en ik heb hulp nodig om het op te lossen:

class TestScores {
    public static void checkscore(int s) {
        if (s<0) throw new IllegalArgumentException("Error: score is negative.");
        else if (s>100) throw new IllegalArgumentException("Error Score is higher then 100");
        else if (s>89)throw new IllegalArgumentException("Your grade is an A");
        else if (s>79 && s<90)throw new IllegalArgumentException("Your grade is an B");
        else if (s>69 && s<80)throw new IllegalArgumentException("Your grade is an C");
        else if (s>59 && s<70)throw new IllegalArgumentException("Your grade is an D");
        else if (s<60)throw new IllegalArgumentException("Your grade is an F");
        {
            int sum = 0; //all elements together
            for (int i = 0; i < a.length; i++)
                sum += a[i];
        }
        return sum / a.length;
    }
}
class TestScoresDemo {
    public static void main(String[] args) {
        int score = 0;
        Scanner scanner = new Scanner(System.in);
        System.out.print(" Enter a Grade number: ");
        String input = scanner.nextLine();
        score = Integer.parseInt(input);
        TestScores.checkscore(score);
        System.out.print("Test score average is" + sum);
    }
}

Ik weet dat de opdracht een try-statement vereist, want in mijn boek zie ik dat met de IllegalArgumentException. Kan iemand mij helpen? Ik gebruik Eclipse als een IDE.


Antwoord 1, autoriteit 100%

Uw klasse TestScores moet twee leden hebben: een constructor die een reeks scores accepteert en een methode die het gemiddelde van de scores retourneert. De opdracht is niet helemaal duidelijk welke van deze een IllegalArgumentException moet geven als een testscore buiten het bereik valt, maar ik zou het de constructor maken (aangezien dat het argument is).

public class TestScores {
    public TestScores(int[] scores) throws IllegalArgumentException {
        // test the scores for validity and throw an exception if appropriate
        // otherwise stash the scores in a field for later use
    }
    public float getAverageScore() {
        // compute the average score and return it
    }
}

Je bent op de goede weg met je TestScoresDemo-les. Het zal eerst een reeks scores in een array moeten verzamelen. Dan zou het een TestScores object moeten construeren. Dit is wat er in een try/catch-blok moet staan, omdat het een uitzondering kan veroorzaken. Dan hoef je alleen maar getAverageScore() aan te roepen en iets met het resultaat te doen.


Antwoord 2

Een uitzondering is iets dat wordt gebruikt om iets te definiëren dat niet goed ging in de normale stroom van een toepassing. Je moet de IllegalArgumentException gooien wanneer de methode checkScore wordt aangeroepen en het vindt elk argument buiten het bereik (tussen 0 en 100).

Je klas zou deze structuur moeten hebben:

public class TestScore {
    private int scores[]; //With setters and getters.
    public TestScore(int scores[]) {
        //Here, you set the scores array to the one on this class.
    }
    public int getAverage() {
        //You do the average here, and since you need to iterate over the 
        //array to sum each value, you can check the value and if it's not
        //ok you throw the IllegalArgumentException. No throws keyword
        //required since this kind of exception (like NullPointerException
        //and many others) are unchecked exceptions, meaning they can be 
        //thrown by a method and it does not need to specify them.
    }
}

De testklasse moet een TestScore-object maken met een int-array als parameter van zijn constructor. Vervolgens maak je een testAverageScore-methode met het try-catch-statement erop, omdat het nodig is om de getAverage-methode aan te roepen.

Ik hoop dat dat helpt. Veel succes!.

EDIT: IllegalArgumentException is een ongecontroleerde uitzondering.


Antwoord 3

public class TestScores {
private final int[] scores;
public TestScores(int[] scores) {
    this.scores = scores;
}
public int getAverage() {
    int sum = 0;
    if(scores.length == 0) {
        return 0;
    }
    for(int score: scores) {
        if(score < 0 || score > 100) {
            throw new IllegalArgumentException("Score is not valid!");
        }
        sum += score;
    }
    return sum/scores.length;
}

}

LEAVE A REPLY

Please enter your comment!
Please enter your name here

six − one =

Other episodes