Let’s assume that we have a simple text file database containing information about students and their majors. The file looks something like the following:
111 Alan Turing computer science 123 Maya Angelou English 456 John Glenn astrophysics 354 Grace Murray Hopper computer science 789 Isaac Netwon astrophysics
Each line consists of a student’s ID number, name, and major, separated by
tab characters (\t
).
We will review a simple Java program for processing this text file database. Also download the text file database and place it in the same folder as the program. We will first run the program to see how it works, and then we’ll explore the source code.
Extend the findStudents()
method so that it prints the total
number of matching student records after reporting all the matches.
Ensure that the total is only printed if there is at least one match. 1
Write a method countRecords()
that opens the data file and counts
how many records are present in the file. Then, add code to call this
method in main()
and print the number of records before waiting for
user input. 2
The MovieDatabase
class is another
example of a simple text file database program. The program asks the user
to enter a movie rating (G, PG, PG-13 or R), and then it should
print the average runtime of all the movies with that rating.
Each line in the
text file database movies.txt
contains a movie title, rating, and runtime, separated by tab characters.
For example, here’s the first line of the file:
Avatar PG-13 162
Before the program will work correctly, we need to find and fix several errors. 3
If we try to run this program, it crashes with an exception. When a program encounters an exception it cannot handle, it stops and prints a message like the following:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at MovieDatabase.findAverageRuntime(MovieDatabase.java:47) at MovieDatabase.main(MovieDatabase.java:26)
This message gives the name of the exception (on the first line, in this
case ArrayIndexOutOfBoundsException
), a brief message describing the problem
(here, it is simply 1
, which is the index that is considered “out of bounds”),
and the sequence of method calls which led to
the exception, with the most “recent” method call at the top. It also shows
the file name of the source code and the line number where the call was
made, for each call. This is called the stack trace or backtrace of
the exception.
When debugging using a stack trace, start at the line number of the most recent method call and work your way down the list until you find the bug.
To help determine the state of the variables of a buggy program as it executes, you may add temporary print statements. For example, in the above program, we can add the following print statements before the problematic line 47.
System.out.println("fields = " + Arrays.toString(fields)); System.out.println("record = " + record); System.out.println("name = " + name);
This will allow us to figure out what values of the variables causes the exception to be thrown.
Once the exception is eliminated, the program still doesn’t work. The number of movies with a particular rating is always 0. This is an example of a logic error — the program doesn’t crash, but we asked Java to do something that isn’t correct for solving our particular problem. We can also use print statements to help diagnose this type of error.
Use temporary print statements to find and fix the remaining problems in the code. Here are some hints:
count++
statement ever executed? How could
you use a print statement to determine if a given block of code is being
executed?Your task is to implement a simple file querying functionality.
Your program will read from the text file mlb.txt
.
Each line of the file has the following format:
Team W L PCT GB
Because of designated tab columns the formatting may look incorrect, but be assured
each field is separated by a tab. The Team column represents the name of the team,
which could be one or more words.
The W column represents the number of wins, an integer.
The L column represents the number of losses, an integer.
The PCT column is the winning percentage, a floating-point number.
The GB column is the games back from first place, which is either
a number or the string "-"
.
For example, here are two lines from the file:
Minnesota 66 96 0.408 27 Chicago 63 99 0.389 30
Your program should allow the user to find the statistics for any team. More specifically, given a team name, the program should find and print the team’s record. Here is a sample run:
Enter a team name (or q to quit): Boston Team W L PCT GB Boston 97 65 0.599 - Enter a team name (or q to quit): q
If the user enters a team that is not in the file, the program should
print a message to that effect. You should first create a program that
asks the user only once for a team name. Then, modify the program so
that it repeatedly asks the user for another team until the user enters
"q"
to quit.
Download the code template in MLB.java
and open it
in VSCode. 4
Using a counter variable is one way to achieve this:
public static void findStudents(String targetMajor) throws FileNotFoundException { Scanner input = new Scanner(new File(DATA_FILENAME)); boolean found = false; // have we found any students? int count = 0; while (input.hasNextLine()) { String record = input.nextLine(); String[] fields = record.split("\t"); int id = Integer.parseInt(fields[0]); String name = fields[1]; String major = fields[2]; if (major.equals(targetMajor)) { found = true; count++; System.out.println(id + "\t" + name); } } if (!found) { System.out.println("No students are majoring in " + targetMajor); } else { System.out.println("Found " + count + " matches"); } }
With the count
variable, we could have also removed the found
flag and change the if
condition to found == 0
. ↩
Here’s one possible implementation of countRecords()
:
public static int countRecords() throws FileNotFoundException { Scanner file = new Scanner(new File(DATA_FILENAME)); int numRecords = 0; while (file.hasNextLine()) { numRecords++; file.nextLine(); } return numRecords; }
Last updated on July 8, 2025.