Skip to content

Commit 2d7dc41

Browse files
committed
Chapter 12 Ex 31
1 parent a9c8b33 commit 2d7dc41

14 files changed

+10222
-2
lines changed

README.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@
66

77
[Click Here to open the Exercise Check Tool](https://liveexample.pearsoncmg.com/CheckExercise/faces/CheckExercise.xhtml?chapter=1&programName=Exercise01_01)
88
____
9-
### <em>Contributors:</em>
10-
##### Harry Dulaney
9+
### <em>Contributors:</em>
10+
11+
### Harry Dulaney
1112
____
1213
### <em>Pull requests:</em>
1314
_I am always excited to get pull requests and will review them quickly._
+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package ch_12.exercise12_30;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.util.Scanner;
6+
7+
/**
8+
* *12.30 (Occurrences of each letter) Write a program that prompts the user to enter
9+
* a file name and displays the occurrences of each letter in the file. Letters are
10+
* case-insensitive. Here is a sample run:
11+
* Enter a filename: Lincoln.txt
12+
* Number of A's: 56
13+
* Number of B's: 134
14+
* ...
15+
* Number of Z's: 9
16+
*/
17+
public class Exercise12_30 {
18+
public static void main(String[] args) {
19+
int[] occurrences = new int[26]; // [# of A's , # of B's, # of C's,...,...] (Index + 65) = uppercase char val
20+
Scanner in = new Scanner(System.in);
21+
System.out.print("Enter a file name: ");// My Test file is: testfile.txt
22+
23+
String fileName = in.next();
24+
File workingDir = new File("." + File.separator + "src" + File.separator + "ch_12" + File.separator +
25+
"exercise12_30" + File.separator);
26+
27+
File file = new File(workingDir, fileName);
28+
29+
if (!file.exists()) {
30+
System.out.println("File does not exist...");
31+
return;
32+
}
33+
try (Scanner fileIn = new Scanner(file)) {
34+
while (fileIn.hasNext()) {
35+
String str = fileIn.next();
36+
for (char ch : str.toCharArray()) {
37+
if (Character.isLetter(ch)) {
38+
occurrences[(Character.toUpperCase(ch) - 65)]++; /* Example: (A - 65) = 0, so int[0]++ */
39+
}
40+
}
41+
}
42+
43+
} catch (IOException ioException) {
44+
ioException.printStackTrace();
45+
}
46+
in.close();
47+
48+
for (int idx = 0; idx < occurrences.length; idx++) {
49+
char ch = (char) (idx + 65);
50+
System.out.println("Number of " + ch + "'s: " + occurrences[idx]);
51+
52+
}
53+
54+
}
55+
}

src/ch_12/exercise12_30/testfile.txt

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
Program Organization
2+
Good computer programs are organized much like good books. This can seen especially well with technical books, in which the structure is very clear.
3+
People have been writing books for hundreds of years, and during that time they have discovered how to organize the material to efficiently present their ideas. Standards have emerged. For example, if I asked you when this book was copyrighted, you would turn to the title page. That's where the copyright notice is always located.
4+
The same goes for code. In fact, we can make the parallels quite explicit.
5+
Any technical book can be analyzed into standard components. So can program. These components correspond quite closely as the following table shows.
6+
Book
7+
Program
8+
Title Page
9+
Heading
10+
Table of Contents
11+
Table of Contents
12+
Chapter
13+
Module
14+
Section
15+
Function
16+
Paragraph
17+
Conceptual Block
18+
Sentence
19+
Statement
20+
Word
21+
Variable
22+
Index
23+
Cross Reference
24+
Glossary
25+
Variable Declaration Comments
26+
These components really do serve the same purposes.
27+
Title Page
28+
A book's title page contains the name of the book, the author, and the publisher. On the reverse of the title page is the copyright page, where you find things like the printing history and Library of Congress information.
29+
At the beginning of every well-documented program is a section known as the heading. It is, in effect, the title page of the program. The heading consists of a set of boxed comments that include the name of the program, the author, copyright, usage, and other important information. The heading comments are fully discussed in See File Basics, Comments, and Program Headings .
30+
Table of Contents
31+
Every technical book has a table of contents. It lists the location of all the chapters and major headings, and serves as a road map to the rest of the book.
32+
A program should have a table of contents as well, listing the location of each function. This is difficult and tedious to produce by hand, however it can be produced quite easily by a number of readily available tools, as discussed later in this chapter.
33+
Chapters
34+
Technical books are divided into chapters, each one covering a single subject. Generally, each chapter in a technical book consists of a chunk of material that a reader can read in one sitting, although this is not a rule: Donald Knuth's highly regarded 624-page Fundamental Algorithms (Addison-Wesley, Reading, MA, 1968) contains only two chapters.
35+
Similarly, a program is divided into modules, each a single file containing a set of functions designed to do some specific job. A short program may consist of just one module, while larger programs can contain 10, 20, or more. Module design is further discussed later in this chapter.
36+
Sections
37+
Each chapter in a technical book is typically divided into several sections. A section covers a smaller body of information than a chapter. Sections in this book are identified by section heads in bold letters, making it easy for a reader to scan a chapter for a particular subject.
38+
Just as a book chapter can contain several sections, a program module may contain several functions. A function is a set of instructions designed to perform a single focused task. A function should be short enough that a programer can easily understand the entire function.
39+
Index
40+
A technical book should have a good index that lists every important subject or keyword in the book and the pages on which it can be found. The index is extremely important in a technical book because it provides quick access to specific information.
41+
A program of any length should have a cross reference, which lists the program variables and constants, along with the line numbers where they are used. A cross reference serves as an index for the program, aiding the programmer in finding variables and determining what they do. A cross reference can be generated automatically by one of the many cross reference tools, such as xref , cref , etc.
42+
Glossary
43+
A glossary is particularly important in a technical book. Each technical profession has its own language, and this is especially true in computer programming (e.g., set COM1 to 1200,8,N, I to avoid PE and FE errors). A reader can turn to the glossary to find the meaning of these special words. Every C program uses its own set of variables, constants, and functions. These names change from program to program, so a glossary is essential. Producing one by hand is impractical, but as you'll see later in this chapter, with a little help from some strategically placed comments, you can easily generate a glossary automatically.
44+
Organize programs for readability, just as you would expect an author to organize a book.
45+
Automatic Generation of Program Documentation
46+
Some of the program components described above can be generated automatically. Consider the table of contents, for example. On UNIX systems, the ctags program will create such a table. Also, there is a public domain program, called cpr , that does the job for both DOS and UNIX.
47+
A cross reference can also be generated automatically by one of the many cross reference tools, such as xref , cref , etc. However, you can also generate a cross reference one symbol at a time. Suppose you want to find out where total-count is located. The command grep searches files for a string, so typing:
48+
grep -n total_count *.c
49+
produces a list of every use of total_count in all the C files. (The -n tells grep to print line numbers.)
50+
The command grep is available both on UNIX systems and in MS-Windows with Borland C++ and Borland's Turbo-C.
51+
Also in UNIX, the command:
52+
vi `grep -l total_count *.c`
53+
invokes the vi editor to list the files that contain the word total_count . Then you can use the vi search command to locate total_count within a file. The commands next ( :next ) and rewind ( :rew ) will flip through the files. See your vi and UNIX manuals for more details.
54+
Borland C++ and Borland's Turbo-C++ have a version of grep built in to the Integrated Develop Environment (IDE). By using the command Alt-Space you can bring up the tools menu, then select grep and give it a command line, and the program will generate a list of references in the message window. The file corresponding to the current message window line is displayed in the edit window. Going up or down in the message changes the edit window. With these commands, you can quickly locate every place a variable is used.
55+
You can also partially automate the process of building a glossary, which is a time-consuming task if performed entirely by hand. The trick is to put a descriptive comment after each variable declaration. That way, when the maintenance programmer wants to know what total_count means, all he or she has to do is look up the first time total_count in mentioned in the cross reference, locate that line in the program, and read:
56+
int total_count; /* total number of items in all classes */
57+
So we have a variable ( total_count ) and its definition: "Total number of items in all classes" -- in other words, a glossary entry.
58+
Module Design
59+
A module is a set of functions that perform related operations. A simple program consists of one file; i.e., one module. More complex programs are built of several modules.
60+
Modules have two parts: the public interface, which gives a user all the information necessary to use the module; and the private section, which actually does the work.
61+
Another analogy to books is helpful here. Consider the documentation for a piece of equipment like a laser printer. This typically consists of two manuals: the Operator's Guide and the Technical Reference Manual.
62+
The Operator's Guide describes how to use the laser printer. It includes information like what the control panel looks like, how to put in paper, and how to change the toner. It does not cover how the printer works.
63+
A user does not need to know what goes on under the covers. As long as the printer does its job, it doesn't matter how it does it. When the printer stops working, the operator calls in a technician, who uses the information in the Technical Reference Manual to make repairs. This manual describes how to disassemble the machine, test the internal components, and replace broken parts.
64+
The public interface of a module is like an Operator's Guide. It tells the programmer and the computer how to use the module. The public interface of a module is called the "header file." It contains data structures, function definitions, and #define constants, which are needed by anyone using the module. The header file also contains a set of comments that tells a programmer how to use the module.
65+
The private section, the actual code for the module, resides in the c file. A programmer who uses the module never needs to look into this file. Some commercial products even distribute their modules in object form only, so nobody can look in the private section.
66+
Divide each module up into a public part (what's needed to use the module) and a private part (what's needed to get the job done). The public part goes into a .h file while the private part goes into a .c file.
67+
Libraries and Other Module Groupings. A library is a collection of generally useful modules combined into a special
68+
object file. Libraries present a special problem: How do you present the public information for a library? Do you use a
69+
single header file, multiple header files for the individual modules, or some other method?
70+
There is no one answer. Each method has its advantages and disadvantages.
+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package ch_12.exercise12_31;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.util.Scanner;
6+
7+
/**
8+
* 12.31 (Baby name popularity ranking) The popularity ranking of baby names from
9+
* years 2001 to 2010 is downloaded from https://www.ssa.gov/oact/babynames and stored
10+
* in files named babynameranking2001.txt, babynameranking2002.txt, . . . ,
11+
* babynameranking2010.txt. Each file contains one thousand lines. Each line
12+
* contains a ranking, a boy’s name, number for the boy’s name, a girl’s name,
13+
* and number for the girl’s name.
14+
* <p>
15+
* For example, the first two lines in the file
16+
* babynameranking2010.txt are as follows:
17+
* <p>
18+
* * 1 Jacob 21,875 Isabella 22,731
19+
* * 2 Ethan 17,866 Sophia 20,477
20+
* <p>
21+
* So, the boy’s name Jacob and girl’s name Isabella are ranked #1 and the boy’s
22+
* name Ethan and girl’s name Sophia are ranked #2. 21,875 boys are named
23+
* Jacob and 22,731 girls are named Isabella.
24+
* <p>
25+
* Write a program that prompts the
26+
* user to enter the year, gender, and followed by a name, and displays the ranking
27+
* of the name for the year.
28+
* Here is a sample run:
29+
* <p>
30+
* Enter the year: 2010
31+
* Enter the gender: M
32+
* Enter the name: Javier
33+
* Javier is ranked #190 in year 2010
34+
* <p>
35+
* Enter the year: 2010
36+
* Enter the gender: F
37+
* Enter the name: ABC
38+
* The name ABC is not ranked in year 2010
39+
*/
40+
public class Exercise12_31 {
41+
private static final String FILENAME_PREFIX = "babynameranking";
42+
private static final String workingDir = "src/ch_12/exercise12_31";
43+
44+
public static void main(String[] args) {
45+
Scanner in = new Scanner(System.in);
46+
System.out.print("Enter the year: ");
47+
int year = in.nextInt();
48+
49+
System.out.print("\nEnter the gender: ");
50+
String gender = in.next().trim();
51+
52+
System.out.print("\nEnter the name: ");
53+
String name = in.next();
54+
55+
int rank = getRank(year, gender.charAt(0), name);
56+
if (rank == -7) {
57+
System.out.println("That name is not on the list for that year....");
58+
}
59+
System.out.print("\n" + name + " is ranked #" + rank + " in year " + year);
60+
61+
in.close();
62+
63+
}
64+
65+
private static int getRank(int year, char gender, String name) {
66+
if (year < 2001 || year > 2010) return -1;
67+
if (gender != 'M' && gender != 'F') return -2;
68+
69+
int ranking = -7; // invalid name default if not set during do while loop
70+
String fileName = FILENAME_PREFIX + year + ".txt";
71+
File file = new File(workingDir, fileName);
72+
73+
try (Scanner fileScanner = new Scanner(file)) {
74+
while (fileScanner.hasNextLine()) {
75+
String[] line = fileScanner.nextLine().split("\\s+"); //Example: 1 Jacob 32,550 Emily 25,057
76+
if (gender == 'M') {
77+
if (line[1].equalsIgnoreCase(name)) {
78+
ranking = Integer.parseInt(line[0].trim());
79+
break;
80+
}
81+
} else {
82+
if (line[3].equalsIgnoreCase(name)) {
83+
ranking = Integer.parseInt(line[0].trim());
84+
break;
85+
}
86+
}
87+
}
88+
89+
} catch (IOException ioException) {
90+
ioException.printStackTrace();
91+
}
92+
return ranking;
93+
}
94+
}

0 commit comments

Comments
 (0)