import java.text.DecimalFormat; /** * Exercise 5.7 p 156
* Each of these method is an attempt to compute the average of 3 integers as * accurately as possible. None of them is correct. There are syntax and logical * errors. Find the error(s) in each one of them.
* Complete also the last method to display a number of hours as hours, minutes * and seconds. */ public class Exercise57 { public double average3A(int n1, int n2, int n3) { // only n3 is divided by 3 // return (double) n1 + (double) n2 + (double) n3 / 3.0; // fix: add parentheses around (double)n1 +... + (double)n3 return ((double) n1 + (double) n2 + (double) n3) / 3.0; } public double average3B(int n1, int n2, int n3) { double result; // don't use new to initialize a double (double is a primitive type) // result = new ((n1+n2+n3)/3.0); // fix: remove new result = ((n1 + n2 + n3) / 3.0); return result; } public double average3C(int n1, int n2, int n3) { double result; // one extra right parenthesis. Fix remove the extra parenthesis // result = (double)(n1+n2+n3)/3.0); result = (double) (n1 + n2 + n3) / 3.0; return result; } public double average3D(int n1, int n2, int n3) { // a cast is written as (double) and not just double // fix: write all of the casts in parentheses // return (double(n1)+double(n2)+double(n3))/3; return ((double) (n1) + (double) (n2) + (double) (n3)) / 3; } /** * Extra pratice: display a number of hours as hh:mm:ss */ public void printAsHMS(double hours) { int h = (int) hours; // what is left hours -= h; // same as hours = hours - h; int m = (int) (hours * 60); // what is left hours -= m / 60.0; int s = Math.round((float) (hours * 3600)); // cast to a float so that // round returns an int and not a long DecimalFormat df = new DecimalFormat("00"); System.out.println(df.format(h) + ":" + df.format(m) + ":" + df.format(s)); } /** * To test */ public static void main(String[] args) { Exercise57 e = new Exercise57(); int n1 = 2, n2 = 3, n3 = 5; // average = (2 + 3 + 4) / 3 = 10/3 = 3.33 System.out.println("average 3A = " + e.average3A(n1, n2, n3)); System.out.println("average 3B = " + e.average3B(n1, n2, n3)); System.out.println("average 3C = " + e.average3C(n1, n2, n3)); System.out.println("average 3D = " + e.average3D(n1, n2, n3)); // 1 hour 10 minutes 17 seconds double hours = 1 + 10.0 / 60.0 + 17.0 / 3600.0; e.printAsHMS(hours); } }