i created a testScores class which initialized an object with an array of scores and had an exception that if the score was <0 or >100 it would throw an IllegalArguementException. I got my main program to work it throws the exception for the array with the bad grade in it and it gives me the correct average for the array with al the good grades.
My question is how do i print the position of the element in the array that the bad grade is and print the grade that threw the exception as well??
testScores class:
public class TestScores
{
private double[] scores;
private double total = 0.0;
public TestScores(double[] s)throws IllegalArgumentException
{
scores = s;
for(int i = 0; i<scores.length;i++)
{
if(scores[i]<0 || scores[i]>100)
throw new IllegalArgumentException("Invalid score found");
total += scores[i];
}
}
public double getAverage()
{
return total/scores.length;
}
}
here is my main
import java.text.DecimalFormat;
public class TestScoresDemo
{
public static void main(String[] args)
{
DecimalFormat formatter = new DecimalFormat("#0.00");
double[] badScores = {97.5, 66.7, 88.0, 101.0, 99.0};
double[] goodScores = {97.5, 66.7, 88.0, 100.0, 99.0};
try
{
TestScores bad = new TestScores(badScores);
System.out.println("Average: " + bad.getAverage());
}
catch(IllegalArgumentException e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
try
{
TestScores good = new TestScores(goodScores);
System.out.println("Average: " + good.getAverage());
}
catch(IllegalArgumentException e)
{
System.out.println(e.getMessage());
}
}
}