Question

In: Computer Science

JAVA Assignment: Project File Processing. Write a program that will read in from input file one...

JAVA Assignment:

Project File Processing.

Write a program that will read in from input file one line at a time until end of file and output the number of words in the line and the number of occurrences of each letter. Define a word to be any string of letters that is delimited at each end by either whitespace, a period, a comma or the beginning or end of the line. You can assume that the input consists entirely of letters, whitespaces, commas and periods. When outputting the number of letters that occur in a line, be sure to count upper and lowercase versions of a letter as the same letter. Output the letters in alphabetical order and list only those letters that do occur in the input line. For example, the input line:-I say HI should produce output similar to the following:-

3 words

1 a

1 h

2 i

1 s

1 y

Please Note!!!!!: in addition to the above, output the result to file named “result.txt”

Solutions

Expert Solution

Program: In this program, we read in a text file, for each line we calculate the number of words in that line, and then for each character of each word we find the frequency of the character. We write the information gathered into an output file. The words in a line are splitted based on different delimiters - commas, periods, spaces, exclamations marks etc.

Below is the implementation:

Code:

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;

class Solution {

    public static void main(String[] args) throws Exception {

        // Create a File class instance and pass input file name
        File file = new File("input.txt");

        // Create FileWriter instance and pass result file name
        FileWriter fileWriter1 = new FileWriter("result.txt");

        // Create scanner class instance and pass file class instance
        Scanner read = new Scanner(file);

        // Read till the end of line
        while (read.hasNextLine()) {

            // Store current line
            String line = read.nextLine();

            // Define regex includes - '!','.',',','_',''','@','?','-' and space
            // we can add more if we want
            String regex = "[!._,'-@? ]";

            // Create a StringTokenizer object and pass line and regex as parameters
            StringTokenizer str = new StringTokenizer(line, regex);

            // Create a list to store words
            List<String> words = new ArrayList<>();

            // Add words to list
            while (str.hasMoreTokens()) {
                words.add(str.nextToken());
            }

            // Number of words in current line
            int numOfWords = words.size();

            // Create an array to store frequency of each character
            int[] freq = new int[26];

            // Traverse each word
            for (String w : words) {

                // Convert it to lowercase
                w = w.toLowerCase();

                // Update frequency for each char of each word
                for (int i = 0; i < w.length(); i++) {
                    freq[w.charAt(i) - 'a']++;
                }
            }

            // Write into file
            fileWriter1.write(numOfWords + " words\n");
            for (int i = 0; i < freq.length; i++) {
                if (freq[i] > 0) {
                    char c = (char) (i + 'a');
                    fileWriter1.write(freq[i] + " " + c + "\n");
                }
            }
        }

        // CLose File and FileWriter instances
        read.close();
        fileWriter1.close();

    }
}

input.txt:

Output (result.txt):

Note: The input file should be saved in the same folder where the current java class is placed.

#Please ask for any doubts. Thanks.


Related Solutions

Please write a java program to write to a text file and to read from a...
Please write a java program to write to a text file and to read from a text file.
Java Write a program that will only accept input from a file provided as the first...
Java Write a program that will only accept input from a file provided as the first command line argument. If no file is given or the file cannot be opened, simply print “Error opening file!” and stop executing. A valid input file should contain two lines. The first line is any valid string, and the second line should contain a single integer. The program should then print the single character from the string provided as the first line of input...
Write a program that takes two sets ’A’ and ’B’ as input read from the file...
Write a program that takes two sets ’A’ and ’B’ as input read from the file prog1 input.txt. The first line of the file corresponds to the set ’A’ and the second line is the set ’B’. Every element of each set is a character, and the characters are separated by space. Implement algorithms for the following operations on the sets. Each of these algorithms must be in separate methods or subroutines. The output should be written in the file...
Write a Java program to read in words from the given file “word.txt”. a. Prompt the...
Write a Java program to read in words from the given file “word.txt”. a. Prompt the user for two words b. Print out how many words in the file fall between those words c. If one of the two words is not contained in the file, print out which word is not found in the file d. If both words are not found in the file, print out a message e. Sample output: Please type in two words: hello computer...
Write a program that takes three sets ’A’, ’B’, ’C’ as input read from the file...
Write a program that takes three sets ’A’, ’B’, ’C’ as input read from the file prog2 input.txt. The first line of the file corresponds to the set ’A’, the second line is the set ’B’, and the third line is the set ’C’. Every element of each set is a character, and the characters are separated by space. Implement algorithms for the following operations on the sets. Each of these algorithms must be in separate methods or subroutines. The...
Write a java program that read a line of input as a sentence and display: ...
Write a java program that read a line of input as a sentence and display:  Only the uppercase letters in the sentence.  The sentence, with all lowercase vowels (i.e. “a”, “e”, “i”, “o”, and “u”) replaced by a strike symbol “*”.
ASSIGNMENT: Write a program and use the attached file (babynames.txt) as input file, and create two...
ASSIGNMENT: Write a program and use the attached file (babynames.txt) as input file, and create two output tiles. One file listing out all boys names, and the other file listing out all girls name. CODE: (teacher gave some of the code below use it to find the answer please String B is the boy names String E is girl names) import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; /** This program reads a file with numbers, and writes the numbers...
ASSIGNMENT: Write a program and use the attached file (babynames.txt) as input file, and create two...
ASSIGNMENT: Write a program and use the attached file (babynames.txt) as input file, and create two output tiles. One file listing out all boys names, and the other file listing out all girls name. CODE: (teacher gave some of the code below use it to find the answer please String B is the boy names String E is girl names) import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; /** This program reads a file with numbers, and writes the numbers...
2. Write a Java program that reads a series of input lines from given file “name.txt”,...
2. Write a Java program that reads a series of input lines from given file “name.txt”, and sorts them into alphabetical order, ignoring the case of words. The program should use the merge sort algorithm so that it efficiently sorts a large file. Contents of names.text Slater, KendallLavery, RyanChandler, Arabella "Babe"Chandler, StuartKane, EricaChandler, Adam JrSlater, ZachMontgomery, JacksonChandler, KrystalMartin, JamesMontgomery, BiancaCortlandt, PalmerDevane, AidanMadden, JoshHayward, DavidLavery,k JonathanSmythe, GreenleeCortlandt, OpalMcDermott, AnnieHenry, DiGrey, MariaEnglish, BrookeKeefer, JuliaMartin, JosephMontgomery, LilyDillon, AmandaColby, LizaStone, Mary FrancesChandler, ColbyFrye, DerekMontgomery,...
Done in C++, Write a program to read the input file, shown below and write out...
Done in C++, Write a program to read the input file, shown below and write out the output file shown below. Use only string objects and string functions to process the data. Do not use c-string functions or stringstream (or istringstream or ostringstream) class objects for your solution. Input File Cincinnati 27, Buffalo 24 Detroit 31, Cleveland 17 Kansas City 24, Oakland 7 Carolina 35, Minnesota 10 Pittsburgh 19, NY Jets 6 Philadelphia 31, Tampa Bay 20 Green Bay 19,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT