// 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.util.Scanner; public class BirthWeightInt { public static final int MaxInput = 20; public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter up to " + MaxInput + " integer values on a line."); Scanner line = new Scanner(input.nextLine( )); // build Scanner with input line int[ ] weights = read(line); // fill array from that Scanner print(weights); System.out.println("Let's look for values in that line you just typed."); System.out.println("Enter value to count: "); while (input.hasNextInt( )) { int target = input.nextInt( ); int answer = countOccurances(weights, target); System.out.println(target + " occurs " + answer + " times"); System.out.println("Enter value to count or type control-d to stop"); } System.out.println("Program finished."); } // 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 int[ ] read(Scanner in) { int count = 0; int[ ] original = new int[MaxInput]; while (count < MaxInput && in.hasNextInt( )) { original[count] = in.nextInt( ); count++; } return rightSizeArray(original, count); } // copy the first 'used' values from original into right-sized array public static int[ ] rightSizeArray(int[ ] original, int used) { int[ ] copy = new int[used]; for (int i = 0; i < used; i++) { copy[i] = original[i]; } return copy; } // print array all on one per line with indexes public static void print(int[ ] a) { for (int i = 0; i < a.length; i++) { System.out.print("[" + i + "] " + a[i] + " "); } System.out.println( ); } // returns how many times target value appears in array public static int countOccurances(int[ ] a, int target) { int count = 0; for (int i = 0; i < a.length; i++) { if ( a[i] == target) { count++; } } return count; } }