30a-section-5-solutions

30a-section-5-solutions - Mehran Sahami CS 106A Handout...

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

View Full Document Right Arrow Icon
Mehran Sahami Handout #30A CS 106A November 2, 2011 Solution to Section #5 Portions of this handout by Eric Roberts 1. Word count /* * File: WordCount.java * -------------------- * Counts the characters, words, and lines in a file. */ import acm.program.*; import java.io.*; public class WordCount extends ConsoleProgram { public void run() { int lines = 0; int words = 0; int chars = 0; BufferedReader rd = openFileReader("File: "); try { while (true) { String line = rd.readLine(); if (line == null) break; lines++; words += countWords(line); chars += line.length(); } rd.close(); } catch (IOException ex) { println("An I/O exception has occurred"); } println("Lines = " + lines); println("Words = " + words); println("Chars = " + chars); } /** * Asks the user for the name of an input file and returns a * BufferedReader attached to its contents. If the file does * not exist, the user is given another chance to try. */ private BufferedReader openFileReader(String prompt) { BufferedReader rd = null; while (rd == null) { String name = readLine(prompt); try { rd = new BufferedReader(new FileReader(name)); } catch (IOException ex) { println("Can't open that file."); } } return rd; }
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 /** * Counts the words (consecutive strings of letters and/or digits) * in the input line. */ private int countWords(String line) { boolean inWord = false; int words = 0; for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); if (Character.isLetterOrDigit(ch)) { inWord = true; } else { if (inWord) words++; inWord = false; } } if (inWord) words++; return words; } } 2. How Unique! /* * File: UniqueNames.java
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 6

30a-section-5-solutions - Mehran Sahami CS 106A Handout...

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

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