Activity 10.2.1.
Try the program below to see the error when N is 0.
avgFirstN()
method expects that N will be greater than 0. If N happens to be 0, an error will occur in the expression sum/N
, because you cannot divide an integer by 0. Try it to see this error./**
* Precondition: N > 0
* Postcondition: avgFirstN() = (1+2+...+N)/N
*/
public double avgFirstN(int N) {
int sum = 0;
for (int k = 1; k <= N; k++)
sum += k;
return sum/N; // What if N is 0?
} // avgFirstN()
/**
* Precondition: N > 0
* Postcondition: avgFirstN() equals (1+2+...+N) divided by N
*/
public double avgFirstN(int N) {
int sum = 0;
if (N <= 0) {
System.out.println(
"ERROR avgFirstN: N <= 0. Program terminating.");
System.exit(0);
}
for (int k = 1; k <= N; k++)
sum += k;
return sum/N; // What if N is 0?
} // avgFirstN()
avgFirstN()
method takes the traditional approach to error handling: Error-handling code is built right into the algorithm. If N happens to be 0 when avgFirstN()
is called, the following output will be generated:ERROR avgFirstN: N <= 0. Program terminating.
avgFirstN()
method is passed an argument of 0 in the CalcAvgTest.main()
. When the JVM detects the error, it will abort the program and print the following message:Exception in thread "main"
java.lang.ArithmeticException: / by zero
at CalcAverage.avgFirstN(Compiled Code)
at CalcAvgTest.main(CalcAvgTest.java:5)
CalcAverage.avgFirstN()
method, which was called by the CalcAvgTest.main()
method.