Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Class : Java Book : Introduction To Java Programming 10th Edition, Comprehensive

ID: 3889107 • Letter: C

Question

Class: Java

Book: Introduction To Java Programming 10th Edition, Comprehensive by Daniel Liang

Problem:

****** Parse the text file by splitting on "[ .,;:!?(){}<>"]", that is call the split method with this parameter: For example, call contents.split("[ .,;:!?(){}<>"]"), where contents is a String object containing the contents of the text file.

Also, explain (in the comment block at the beginning of the source file) two other approaches that could have been taken for the problem (use of other data structures, perhaps?) and why you chose the approach you took as opposed to the alternatives. Compare and contrast your approach relative to these other approaches in terms of coding complexity, performance, and memory usage. ******

21.2 (Display nonduplicate words in ascending order) Write a program that reads words from a text file and displays all the nonduplicate words in ascending order The text file is passed as a command-line argument.

Explanation / Answer

import java.util.*;
import java.io.*;

public class Exercise_21_02 {
    public static void main(String[] args) throws Exception {
        // Check length of command-line argument
        if (args.length != 1) {
            System.out.println("Usage: java fileName");
            System.exit(1);
        }

        // Check if file exists
        File textFile = new File(args[0]);
        if (!textFile.exists()) {
            System.out.println("The file " + args[0] + " does not exist.");
            System.exit(2);
        }

        // Create a set
        TreeSet<String> set = new TreeSet<>();

        // Read nonduplicate words from the file
        try ( // Create an input file
              Scanner input = new Scanner(textFile);
        ) {
            while (input.hasNext()) {
                String[] words = input.nextLine().split("[ .,;:!?()-]");
                for (String word: words) {
                    if (word.length() > 0)
                        set.add(word.toLowerCase());
                }
            }
        }

        // Display nonduplicate word in ascending order
        System.out.println(set);
    }
}