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

Write a main() method that does the following assuming that all needed packages

ID: 3833884 • Letter: W

Question

Write a main() method that does the following assuming that all needed packages are imported:

read all input lines from an input file, retrieve all words from all input lines taken and store them into an array of Strings,named arrayWords separated by the following six delimiters:

,           // comma

.           // period

?

;

            // blank space

:           // colon

sort these words in alphabetically ascending order using predefined sort() method and print sorted array of words using the Enhanced for loop (or for-each loop).

Explanation / Answer

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Sample {

    private static final String FILENAME = "C:\Users\Junaid\Desktop\Sample.txt"; // provide your file path

    public static void main(String[] args) {
        String[] arrayWords;
        BufferedReader bufferedReader = null;
        FileReader fileReader = null;
        StringBuffer stringBuffer = null;
        String currentLine = "";
        int index = 0;
        try {
            stringBuffer = new StringBuffer();
            bufferedReader = new BufferedReader(new FileReader(FILENAME));

            while ((currentLine = bufferedReader.readLine()) != null) {
                stringBuffer.append(currentLine);
            }
            StringTokenizer stringTokenizer = new StringTokenizer(stringBuffer.toString(), ",.?;: ");
            arrayWords = new String[stringTokenizer.countTokens()];
            while (stringTokenizer.hasMoreTokens()) {
                arrayWords[index] = stringTokenizer.nextToken();
                index++;
            }
            Arrays.sort(arrayWords);
            for (String word : arrayWords) {
                System.out.println(word);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote