Structured Text File: 6 Exercises

After we learned the classes and methods related to the File I/O, we did 6 exercises to test our understanding. In this blog post, I will focus on these six exercises and my reflection about them.

Questions and Answers

Q1

Write a program that reads a file that contains only one line; output all the characters, one character per line.1

Here is the result of the program. I used the method from Scanner Class, useDelimiter(), to separate every character. Since the question asks me to print all the characters line by line, I used the delimiter “”.

Q2

Write a program that reads a file and counts how many lines it contains.

2

I think this problem is simpler than the previous one, since what I need to do is construct a while loop using “inputStream.hasNextLine()”, while using a integer variable to record the time of looping.

Q3

Write a program that reads a text file that contains a grade (for instance, 87) on each line. Calculate and print the average of the grades.

  1. 3

This problem requires a similar algorithm as the previous one, as we need to use

inputStream.hasNextLine()

Then, we put the each line in a variable, and add them together. However, there is a problem because the data type of the lines is String. Therefore, we can use wrapper class, Integer, to convert the String into integer data type. This is what I used:

item = Integer.parseInt(line);

Also, we need a try catch block to handle the error “InputMismatchException.”

Q4

Design a class that checks if the contents of two text files are identical and, if not, determines how many lines are different. //Lines are different if they differ in one or more characters.//Test your class with a client program, which contains main() method

4

To deal with this seeming difficult problem, I first create a Scanner for the two InputStreams, which are the two files. Then, I use the a while loop to count the same lines. I wrote three conditions: The first has next line; the second has next line; they are equal (represented by a boolean variable declared in advance). Here are the codes for this part:

int number = 0;
int a = 0;
int b = 0;
boolean equal = true;
while (input1.hasNextLine() && input2.hasNextLine() && equal){
    String garbage1 = input1.nextLine();
    String garbage2 = input2.nextLine();
    if(garbage1.equals(garbage2)){
        number ++;
    } else {
        a += 1;
        b += 1;
        equal = false;
    }
}

To read the text line by line, I used garbage variables to accept the data in each line while counting the number of lines. After finding the number of same lines, I used two while loops to count lines that are left out, which gives me the number of different lines.

Q5

In Internet programming, programmers receive parameters via a query string, which looks like a String with fields separated by the “&” character. Each field typically has a metadata part and a data part separated by the equal sign. An example of a query string is: “first=Mike&last=Jones&id=mike1&password=hello”

Using Scanner at least once, parse a query string and output each field on a different line after replacing the equal sign with a colon followed by a space. For example, for the preceding sample query string, the output should be: first: Mikelast: Jonesid: mike1password: hello

5

The aim is to re-format the line. So I must use delimiter to separate the line with “&” and then “=”. I chose to use ArrayList to gather all the lines, since it is easy for me to go through each item it the list. Firstly, I use the delimiter “&” and put each item in an ArrayList named “info.” Then, here is what I got for the second delimiter:

int i = 0;
for (String item: info){
    Scanner parse2 = new Scanner(item);
    parse2.useDelimiter("=");
    info.set(i,"" + parse2.next() + ": " + parse2.next());
    i++;
}

I initialise an integer i control the number of the loop. Also, it provides me index so that I can use the method “.set(index,argument)” this for each loop. In the argument, I formatted the line in my own way.

Q6

Design a class that attempts to determine the relative frequency of each letter by reading a file and keeping track of the number of times each of the 26 English alphabet characters appears.Also provide methods, such as highestFrequencyCharacter and lowestFrequencyCharacter.Test your class with a client program.

6

This program is a little tricky. Firstly, to separate all the characters, I used delimiter “” again. I create a method which takes the file name and a character as arguments. Inside the method, I use while loop and an integer variable to record the number of times that the character appears. When I get the character, I use charAt(0) for each line I separated using delimiter.

 

Real Life Implication

There are many real life implications of these exercises. The first program can be improved to be able to count characters. The second one is useful because it can count line in a file. The third can be used by teachers to calculate the average grade out of a file that records all the grades. The fifth one can be used when we need to unpack some messages that have particular pattern. It’s very useful for changing the format of some documents. The six one can be used in cryptography, since determining the frequency of characters can help us discover the plain code of a cypher.

Conclusion

By doing these exercises, we solidified our knowledge about File I/O. Also, I am inspired by these programs so that I can create some similar programs to solve my daily-life problems. It’s so much fun to create programs that do complicated jobs!

Leave a comment

Website Built with WordPress.com.

Up ↑