/** * Test1 * The program builds a two-dimensional array of characters * Input is pairs of strings where the first character of * the first input string is the character to be found and * the first character of the second input string is the one * to be substituted for the first * * Author: Beth Katz * February 2008 */ import java.io.*; import java.util.*; public class Test1 { public static void main(String[ ] args) { Scanner console = new Scanner(System.in); char [][] array = new char[][] { {'h','b','t','n','r','o','c','h'}, {'a','o','e','h','a','n','r','k'}, {'m','o','a','i','s','g','a','g'}, {'i','t','i','v','p','c','n','i'}, {'r','a','u','i','o','i','b','n'}, {'g','t','e','r','f','i','e','d'}, {'l','o','n','f','k','n','r','i'}, {'i','p','u','m','g','e','r','a'}, {'p','t','g','r','a','v','y','n'}, {'s','q','u','a','s','h','a','m'}}; char target, sub; String input; print(array); System.out.println("\nEnter a char to find and a char to replace it with:"); try { while(console.hasNext( )) { input = console.next( ); target = input.charAt(0); input = console.next( ); sub = input.charAt(0); System.out.println(replaceReport(array, target, sub)); print(array); System.out.println("\nEnter a char and its replacement:"); } } catch (NoSuchElementException e) { System.out.println("Enter pairs of strings. Quitting."); } } /** * substitutes subCh for orig in array a and returns how many * substitutions were made */ public static int replace(char[][] a, char orig, char subCh) { int count = 0; for (int r = 0; r < a.length; r++) { for (int c = 0; c < a[r].length; c++) { if (a[r][c] == orig) { a[r][c] = subCh; count++; } } } return count; } /** * substitutes subCh for orig in array a and reports on what happened */ public static String replaceReport(char[][] a, char orig, char subCh) { int times = replace(a, orig, subCh); if (times == 0) { return "No replacements"; } else { String answer = new String(times + " replacements"); return (answer); } } /** * prints the array neatly */ static void print(char[][] a) { for (int r = 0; r < a.length; r++) { for (int c = 0; c < a[r].length; c++) { System.out.print(a[r][c] + " "); } System.out.println( ); } } }