import java.util.Scanner; /** * Contains example methods for lecture, about loops. */ public class ArrayDemos { private static Scanner s = new Scanner(System.in); private static final int NUM_DATA = 365; /** Return the largest value in a double[]. * @param data The array to find the max value in. * Pre-condition: Must be non-empty (data.length > 0.) * @return the largest value in data. */ public static double max( double[] data ) { return -1; } /** Return the index of a largest value in a double[]. ("argmax"). * @param data The array to find the max value in. * Pre-condition: Must be non-empty (data.length > 0.) * @return the index of a largest value in data. * If the largest value occurs several times, we return the index of * the ???? occurrence. */ public static int indexOfMax( double[] data ) { return -1; } public static double maxConsecutivePair( double[] data ) { return -1; } public static int countOccurrences( String wrd, char target ) { return -1; } public static int countOccurrences( String[] wrd, char target ) { return -1; } public static String arrayToString( double[] wrd ) { return "blah"; } public static void rainfallExample() { double[] rain; rain = new double[NUM_DATA]; int indx = 0; while (indx < rain.length) { System.out.println("Please enter the rainfall for day #" + indx ); rain[indx] = s.nextDouble(); indx = indx + 1; } // what is the total rainfall? //rain[0] + rain[1] + rain[2] + rain[3] + rain[4] + rain[5] // Hmm, that doesn't scale to (say) array-length 365: // Instead: write a loop. double totalRainSoFar = 0.0; for ( int i = 0; i < rain.length; i += 1 ) { totalRainSoFar += rain[i]; } System.out.println("average rainfall is " + totalRainSoFar/rain.length ); } // public static int indexOf( String s, char target ) { int i = 0; boolean seenSoFar = false; while (i < s.length() && !seenSoFar) { if (s.charAt(i) == target) { seenSoFar = true; // cause the loop to stop } i += 1; } return i; // the index IS our accumulated answer in this case! } public static int indexOf_v2( String s, char target ) { int i = 0; boolean seenSoFar = false; while (i < s.length() && !seenSoFar) { // update accum to: "previously seen, or we're seeing it now" seenSoFar = seenSoFar || (s.charAt(i) == target); i += 1; } return i; // the index IS our accumulated answer in this case! } public static int indexOf_v3( String s, char target ) { int i = 0; while ( target != s.charAt(i) && i < s.length() ) { i += 1; } return i; } public char[] wordFreqs() { // How to represent histogram's info? while (s.hasNext()) { // read one word, count its letters, adding them to our histogram } // return resulting histogram return new char[0]; // Stub -- an array with 0 locations (!) } }