Docsity

Files, Arrays, and ArrayLists - Section Handout - Programming Methodology- 30, Exercises of Programming Methodologies

Toggle sidebar
bg1
Mehran Sahami Handout #30
CS 106A October 29, 2007
Section Handout #5: Files, Arrays, and ArrayLists
Portions of this handout b y Eric Roberts
1. Word count
Write a program
WordCount
that reads a file and reports how many lines, words, and
characters appear in it. Suppose, for example, that the file
lear.txt
contains the
following passage from Shakespeare’s King Lear:
Poor naked wretches, wheresoe'er you are,
That bide the pelting of this pitiless storm,
How shall your houseless heads and unfed sides,
Your loop'd and window'd raggedness, defend you
From seasons such as these? O, I have ta'en
Too little care of this!
Given this file, your program should be able to generate the following sample run:
For the purposes of this program, a word consists of a consecutive sequence of letters
and/or digits, which you can test using the static method
Character.isLetterOrDigit
.
Also, you should not count the characters that mark the end of a line, which will have
different values depending on the type of computer.
pf3
pf4
pf5

Partial preview of the text

Download Files, Arrays, and ArrayLists - Section Handout - Programming Methodology- 30 and more Exercises Programming Methodologies in PDF only on Docsity!

Mehran Sahami Handout

CS 106A October 29, 2007

Section Handout #5: Files, Arrays, and ArrayLists

Portions of this handout by Eric Roberts

1. Word count

Write a program WordCount that reads a file and reports how many lines, words, and

characters appear in it. Suppose, for example, that the file lear.txt contains the

following passage from Shakespeare’s King Lear:

Poor naked wretches, wheresoe'er you are, That bide the pelting of this pitiless storm, How shall your houseless heads and unfed sides, Your loop'd and window'd raggedness, defend you From seasons such as these? O, I have ta'en Too little care of this!

Given this file, your program should be able to generate the following sample run:

For the purposes of this program, a word consists of a consecutive sequence of letters

and/or digits, which you can test using the static method Character.isLetterOrDigit.

Also, you should not count the characters that mark the end of a line, which will have

different values depending on the type of computer.

2. Histograms

Write a program that reads a list of exam scores from the file

MidtermScores.txt (which contains one score per line) and

then displays a histogram of those numbers, divided into the

ranges 0–9, 10–19, 20–29, and so forth, up to the range

containing only the value 100. If, for example,

MidtermScores.txt contains the data shown in the right

margin, your program should then be able to generate a

histogram that looks as much as possible like the following

sample run:

MidtermScores.txt 73 58 73 93 82 62 80 53 93 52 92 75 65 95 23 100 75 38 80 77 92 60 98 95 62 87 97 73 78 72 55 58 42 31 78 70 78 74 70 60 72 75 84 87 62 17 92 78 74 65 90

Mehran Sahami Handout #30A

CS 106A November 1, 2007

Solution to Section

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; }
  • 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. Histogram

  • File: Histogram.java

  • This program reads a list of exam scores, with one score per line.
  • It then displays a histogram of those scores, divided into the
  • ranges 0–9, 10–19, 20–29, and so forth, up to the range containing
  • only the value 100. */

import acm.program.; import acm.util.; import java.io.*;

public class Histogram extends ConsoleProgram {

public void run() { initHistogram(); readScoresIntoHistogram(); printHistogram(); }

/* Initializes the histogram array */ private void initHistogram() { histogramArray = new int[11]; for (int i = 0; i <= 10; i++) { histogramArray[i] = 0; } }

  • 4 –

3. Unique Names

  • File: UniqueNames.java

  • This program asks the user for a list of names (one per line)
  • until the user enters a blank line. Then the program prints
  • out the list of names entered, where each name is listed only
  • once (i.e., uniquely) no matter how many times the user entered
  • the name in the program. */

import acm.program.; import java.util.;

public class UniqueNames extends ConsoleProgram {

public void run() { ArrayList list = new ArrayList(); while (true) { String name = readLine("Enter name: "); if (name.equals("")) break; if (!list.contains(name)) { list.add(name); } }

println("Unique name list contains:"); printList(list); }

/* Prints out contents of ArrayList, one element per line */ private void printList(ArrayList list) { for(int i = 0; i < list.size(); i++) { println(list.get(i)); } }

}