// Report on animal birth weights as entered by user // Do not change your growth program to use this reading approach // Beth Katz - April 2009 import java.text.DecimalFormat; import java.util.Scanner; public class BirthWeight2 { public static final int MaxInput = 20; public static final DecimalFormat fmt = new DecimalFormat("0.0"); public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter up to " + MaxInput + " real values."); double[ ] weights = read(input); print(weights); System.out.println("5 occurs " + countOccurances(weights, 5) + " times"); } // read many values from a Scanner and copy them into an array // just big enough to hold them // returns array holding up to MaxInput values // see p. 393 of text public static double[ ] read(Scanner in) { int count = 0; double[ ] original = new double[MaxInput]; while (count < MaxInput && in.hasNextDouble( )) { original[count] = in.nextDouble( ); count++; } return rightSizeArray(original, count); } // print array all on one per line with indexes public static void print(double[ ] a) { for (int i = 0; i < a.length; i++) { System.out.print("[" + i + "] " + fmt.format(a[i]) + " "); } System.out.println( ); } // copy as many values as were read into right-sized array public static double[ ] rightSizeArray(double[ ] original, int count) { double[ ] copy = new double[count]; for (int i = 0; i < count; i++) { copy[i] = original[i]; } return copy; } // returns how many times target value appears in array public static int countOccurances(double[ ] a, double target) { int count = 0; for (int i = 0; i < a.length; i++) { if ( a[i] == target) { count++; } } return count; } }