Post

Created by @nathanedwards
 at October 31st 2023, 9:15:48 pm.

AP Computer Science Exam - File Classes in Java

Question:

Write a Java program that reads a text file and performs the following operations:

  1. Calculates the total number of lines in the file.
  2. Calculates the total number of words in the file.
  3. Calculates the average number of characters per word in the file.
  4. Finds the longest word in the file.

You can assume that the text file is named "input.txt" and is located in the same directory as the Java program file.

Instructions:

  1. You should use appropriate file handling classes in Java to read the text file.
  2. Implement a method findLongestWord to find the longest word in a given string and return it. You may assume that the string contains only words (no punctuation marks or special characters).
  3. Return the calculated values as an object of a class named FileStats, which should have appropriate getters for each statistic.

Class Signature:

class FileStats {
    private int totalLines;
    private int totalWords;
    private double averageCharsPerWord;
    private String longestWord;

    // Constructors, getters, and setters (if needed) go here
}

Method Signature:

public static FileStats getFileStats(String filename) throws IOException {
    // Method implementation goes here
}

Example usage:

try {
    FileStats stats = getFileStats("input.txt");
    System.out.println("Total lines: " + stats.getTotalLines());
    System.out.println("Total words: " + stats.getTotalWords());
    System.out.println("Average characters per word: " + stats.getAverageCharsPerWord());
    System.out.println("Longest word: " + stats.getLongestWord());
} catch (IOException e) {
    System.out.println("An error occurred: " + e.getMessage());
}

Answer:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class FileStats {
    private int totalLines;
    private int totalWords;
    private double averageCharsPerWord;
    private String longestWord;

    public FileStats(int totalLines, int totalWords, double averageCharsPerWord, String longestWord) {
        this.totalLines = totalLines;
        this.totalWords = totalWords;
        this.averageCharsPerWord = averageCharsPerWord;
        this.longestWord = longestWord;
    }

    public int getTotalLines() {
        return totalLines;
    }

    public int getTotalWords() {
        return totalWords;
    }

    public double getAverageCharsPerWord() {
        return averageCharsPerWord;
    }

    public String getLongestWord() {
        return longestWord;
    }
}

public class FileStatsExample {
    public static FileStats getFileStats(String filename) throws IOException {
        int totalLines = 0;
        int totalWords = 0;
        double totalChars = 0.0;
        String longestWord = "";

        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                totalLines++;
                String[] words = line.split("\\s+");
                totalWords += words.length;
                for (String word : words) {
                    if (word.length() > longestWord.length()) {
                        longestWord = word;
                    }
                    totalChars += word.length();
                }
            }
        }

        double averageCharsPerWord = totalChars / totalWords;
        return new FileStats(totalLines, totalWords, averageCharsPerWord, longestWord);
    }

    public static void main(String[] args) {
        try {
            FileStats stats = getFileStats("input.txt");
            System.out.println("Total lines: " + stats.getTotalLines());
            System.out.println("Total words: " + stats.getTotalWords());
            System.out.println("Average characters per word: " + stats.getAverageCharsPerWord());
            System.out.println("Longest Word: " + stats.getLongestWord());
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

In this solution, the getFileStats method reads the text file line by line using a BufferedReader, and splits each line into words using the regular expression \\s+. It then updates the total lines, total words, total characters, and longest word variables accordingly.

Finally, it calculates the average characters per word and returns an instance of the FileStats class with all the calculated statistics.

The main method demonstrates the usage of the getFileStats method by printing out the calculated statistics.