// CSE 142, Summer 2008, Helene Martin // Array parameter and return practice. // String traversal practice. // Notice that we have overloaded methods -- same name, different parameters. import java.util.*; public class Practice { public static void main(String[] args) { int[] nums0 = {3, 5, 9, 5}; int count = count(nums0, 5); System.out.println("5 count: " + count); int[] nums = {4, -2, 6, 23, -5, 4, 6, 4}; System.out.println(Arrays.toString(nums)); replace(nums, 4, 5); // Should result in {5, -2, 6, 23, -5, 5, 6, 5} System.out.println(Arrays.toString(nums)); ///////////////STRINGS///////////////// int hCount = count("Oscar the grouch", 'h'); System.out.println("h appearances: " + hCount); String newVerse = replace("eat apples and bananas", 'a', 'o'); // Should result in "eot opples ond bononos" System.out.println("a replaced: " + newVerse); } // Replaces all instances of ch1 in String with ch2 // Note that Strings can't be changed, so we have to return // a new one that we build up. public static String replace(String s, char ch1, char ch2) { String replaced = ""; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == ch1) { replaced = replaced + ch2; } else { replaced = replaced + s.charAt(i); } } return replaced; } // Counts and returns occurences of target character in String. public static int count(String s, char ch) { int count = 0; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == ch) { count++; } } return count; } // Replaces all instances of val1 in array with val2 // No need to return because of reference semantics public static void replace(int[] array, int val1, int val2) { for(int i = 0; i < array.length; i++) { if(array[i] == val1) { array[i] = val2; } } } // Counts and returns occurences of target in array. public static int count(int[] array, int target) { int counter = 0; for (int i = 0; i < array.length; i++) { if(array[i] == target) { counter++; } } return counter; } }