34a-section-6-solutions

34a-section-6-solutions - readNames(nameMap);...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Mehran Sahami Handout #34A CS 106A November 7, 2007 Solutions to Section #6 1. Image processing private GImage flipHorizontal(GImage image) { int[][] array = image.getPixelArray(); int width = array[0].length; int height = array.length; for (int row = 0; row < height; row++) { for (int p1 = 0; p1 < width / 2; p1++) { int p2 = width - p1 - 1; int temp = array[row][p1]; array[row][p1] = array[row][p2]; array[row][p2] = temp; } } return new GImage(array); } Solution for Problem #2 Name Counts on back of page.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 2. Name Counts /* * File: CountNames.java * --------------------- * This program shows an example of using a HashMap. It reads a * list of names from the user and list out how many times each name * appeared in the list. */ import acm.program.*; import java.util.*; public class CountNames extends ConsoleProgram { public void run() { HashMap<String,Integer> nameMap = new HashMap<String,Integer>();
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: readNames(nameMap); printMap(nameMap); } /* * Reads a list of names from the user, storing names and how many * times each appeared in the map that is passed in as a parameter. */ private void readNames(Map&lt;String,Integer&gt; map) { while (true) { String name = readLine(&quot;Enter name: &quot;); if (name.equals(&quot;&quot;)) break; // See if that name previously appeared in the map. Update // count if it did, or create a new count if it didn't. Integer count = map.get(name); if (count == null) { count = new Integer(1); } else { count = new Integer(count + 1); } map.put(name, count); } } /* * Prints out list of entries (and associated counts) from the map * that is passed in as a parameter. */ private void printMap(Map&lt;String,Integer&gt; map) { Iterator&lt;String&gt; it = map.keySet().iterator(); while (it.hasNext()) { String key = it.next(); int count = map.get(key); println(&quot;Entry [&quot; + key + &quot;] has count &quot; + count); } } }...
View Full Document

Page1 / 2

34a-section-6-solutions - readNames(nameMap);...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online