import java.util.Arrays; import uwcse.io.Input; public class ArrayExample { public static void main(String[] args) { // create an array of double elements of size 5 double[] a = new double[5]; // input 5 floating point numbers and store them in the // array // write length and NOT length(). length is a field and // not a method Input in = new Input(); for (int i = 0; i < a.length; i++) { a[i] = in.readDouble("Enter a floating point number: "); } // display the array using the format // [1.2, 3.4, 5.5, 6.7, -1.3] String s = "["; for (int i = 0; i < a.length; i++) { s += a[i]; // fence post problem: add a , only if it is not // the last element if (i < a.length - 1) { s += ", "; } } s += "]"; System.out.println(s); // could also use the method toString in the Arrays class System.out.println(Arrays.toString(a)); // average, max and min double sum = 0; // for-each loop for (double x: a) { sum += x; } System.out.println("average = " + sum/a.length); double max = a[0]; // could also use -Double.MAX_VALUE; double min = a[0]; // could also use Double.MAX_VALUE; for (int i = 1; i < a.length; i ++) { if (a[i] > max) { max = a[i]; } if (a[i] < min) { min = a[i]; } } System.out.println("max = " + max); System.out.println("min = " + min); // can't change the length of a directly // a.length += 2 doesn't work // to add 2 elements to a, do the following // create an array b that has length = a.length + 2 double[] b = new double[a.length + 2]; // copy a in b for (int i = 0; i < a.length; i ++) { b[i] = a[i]; } // rename the array b a a = b; } }