/** * @author Robert W. Hasker * Fall, 2013 */ import java.util.Scanner; public class Main { /** * Print message and then read words from standard input and * place them into the array. Stops reading words when END * is entered. * @param prompt Message printed before reading words * @param words Destination array; must pass in an array * that is of sufficient size. * @return Number of words read. */ static int readWords(String prompt, String[] words) { System.out.print(prompt); int count = 0; Scanner word_input = new Scanner(System.in); String next_word = word_input.next(); while ( !next_word.equals("END")) { words[count] = next_word; count++; next_word = word_input.next(); } return count; } /* * Code to test creating, reading, printing, and processing an array * of strings. */ public static void main(String[] args) { String[] names = new String[100]; int numNames = 0; numNames = readWords("Enter list of names, with END to quit.\n", names); for(int i = 0; i < numNames; i++) System.out.println(names[i]); // count number of times Matt appears in names[] int count = 0; for(int i = 0; i < numNames; i++) if ( names[i].equals("Matt")) count++; System.out.println("Matt occurs " + count + " times"); // is target in list of names? String target = "Zina"; int name_index = 0; while ( name_index < numNames && !names[name_index].equals(target) ) name_index++; if ( name_index < numNames ) System.out.println(target + " found"); else System.out.println(target + " NOT found"); } }