Question

In: Computer Science

Java project// please explain every statement with reasoning. Thank you Mary had a little lamb whose...

Java project// please explain every statement with reasoning. Thank you

Mary had a little lamb
whose fl33ce was white as sn0w
And everywhere that @Mary went
the 1amb was sure to go.

Read from a file that contains a paragraph of words. Put all the words in an array, put the valid words (words that have only letters) in a second array, and put the invalid words in a third array. Sort the array of valid words using Selection Sort. Create a GUI to display the arrays using a GridLayout with one row and three columns.

The input file

Each line of the input file will contain a sentence with words separated by one space. Read a line from the file and use a StringTokenizer to extract the words from the line.

An example of the input file would be:

Mary had a little lamb
Whose fl33ce was white as sn0w.

You should have two files to submit for this project:

Project1.java

WordGUI.java

Solutions

Expert Solution

Project1.java:
---------------

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

public class Project1 
{
        public static void main(String args[])
        {
                File file=null;    
                FileReader fr=null;  
                BufferedReader br=null;    
                String line;  
                StringTokenizer st = null; 
                
                int numberOfWordsInFile;
                
                String words[];
                int index;
                
                String validWords[];
                int validWordsIndex;
                
                String invalidWords[];
                int invalidWordsIndex;
                try  
                {  
                        //Creates instance for the input file
            //Update the path here as per the path of your input file in your system
                        file=new File("C:\\Users\\skarri4\\Desktop\\input.txt");  
                        
                        //Reads from the file
                        fr=new FileReader(file);
                        
                        //Creates a Buffer for Character Stream
                        br=new BufferedReader(fr);    
                        
                        //Update this variable value based on number of words in the file, as array requires index length to be specified statically, for dynamic length use ArrayList
                        numberOfWordsInFile = 22;
                        
                        //Creating array to hold words in the file
                        words = new String[numberOfWordsInFile];
                        
                        //index to point to the words in words array
                        index=0;
                        
                        //Reads content from file line by line
                        while((line=br.readLine())!=null)  
                        {  
                                //Makes the line into words
                                st = new StringTokenizer(line);
                                
                                //checking whether there are words in the line
                                while(st.hasMoreElements()) 
                                {
                                        //if there are tokens, adding each word to the 'words' array
                                        words[index]=(String)st.nextElement();
                                        //incrementing the index to move to next index in the 'words' array
                                        index++;
                                }
                        }  
                        //As whole data is read from the file, closing the file
                        fr.close();  
                        
                        //intialising the 'validWords' array with length same as 'words' array, as we do not know how many words are valid
                        validWords = new String[numberOfWordsInFile];
                        //validWordsIndex is an index to point to the words in 'validWords' array
                        validWordsIndex = 0;
                        
                        //intialising the 'invalidWords' array with length same as 'words' array, as we do not know how many words are valid
                        invalidWords = new String[numberOfWordsInFile];
                        //invalidWordsIndex is an index to point to the words in 'invalidWords' array
                        invalidWordsIndex = 0;
                        
                        //Chcking each word in 'words' array whether it has only letters, if yes adding them to 'validWords' array or else adding them to 'invalidWords' array
                        for(int i=0;i<words.length;i++)
                                if((!words[i].equals("")) 
                                    && (words[i] != null) 
                                    && (words[i].matches("^[a-zA-Z]*$"))) 
                                {
                                        validWords[validWordsIndex]=words[i];
                                        validWordsIndex++;
                                }
                                else 
                                {
                                        invalidWords[invalidWordsIndex]=words[i];
                                        invalidWordsIndex++;
                                }

                        //Calling selectionSort() method, defined in this class, to sort elements of 'validWords' array
                        selectionSort(validWords, validWordsIndex);
                        
                        //Creating object for WordGUI class to access its methods
                        WordGUI wg = new WordGUI();
                        
                        //Passing the three arrays along with their index values to display in Grid
                        wg.display(words, index, validWords, validWordsIndex, invalidWords, invalidWordsIndex);
                }  
                catch(IOException e)  
                {  
                        e.printStackTrace();  
                }  
                catch(Exception e)  
                {  
                        e.printStackTrace();  
                } 
        }
        
        //This method sorts the elements in 'validWords' array using Selection sort
        static String[] selectionSort(String[] validWords, int validWordsIndex) {
                
                //i passes from 0 to arraylength - 1
                for(int i = 0; i < validWordsIndex - 1; i++) 
                { 
                        //This is minimum element in an unsorted array
                        int min_index = i; 
                        String minStr = validWords[i]; 
                        //j passes from i+1 to arraylength
                        for(int j = i + 1; j < validWordsIndex; j++)  
                        {
                                //if current array element is smaller than minimum element, compareTo() returns -ve value
                                if(validWords[j].compareTo(minStr) < 0)  
                                {       
                                        //Then makes current array element as minimum element
                                        minStr = validWords[j]; 
                                        min_index = j; 
                                } 
                        } 
                        //Swapping minimum element with first element in this iteration
                        if(min_index != i) 
                        { 
                                String temp = validWords[min_index]; 
                                validWords[min_index] = validWords[i];  
                                validWords[i] = temp;  
                        } 
                }
                return validWords;
        }
}


WordGUI.java:
-------------
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class WordGUI {

        public void display(String[] words, int index, String[] validWords, int validWordsIndex, String[] invalidWords, int invalidWordsIndex)
        {
                JFrame f = new JFrame();
                //Setting grid layout of 1 row and 3 columns
                f.setLayout(new GridLayout(1,3));
            
                //label object to hold label of each cell
            String label = "";
            
            //Convert 'words' array to label with multiple lines to display in single row as mentioned in the question statement
            label = convertArrayToLabel(words, index);
            //Add label to Grid
            f.add(new JLabel(label));
                
            //Convert 'validWords' array to label with multiple lines to display in single row as mentioned in the question statement
            label = convertArrayToLabel(validWords, validWordsIndex);
            //Add label to Grid
            f.add(new JLabel(label));
            
            //Convert 'invalidWords' array to label with multiple lines to display in single row as mentioned in the question statement
            label = convertArrayToLabel(invalidWords, invalidWordsIndex);
            //Add label to Grid
            f.add(new JLabel(label));
            
            //Set window size
                f.setSize(1000,1000);
                //Set visiblity to True
            f.setVisible(true);
        }
        
        //This method accepts an array and number of elements in it and converts the array to a String
        public String convertArrayToLabel(String[] array, int maxIndex) {
                //Takes each element in the array and adds it to the String, that contains <html> syntax, to display array in multiple lines in a label
                String label = "<html>";
            for(int i=0;i<maxIndex;i++) {
                label = label + array[i] + "<br/>";
            }
            label = label + "</html>";
            return label;
        }
}


input.txt:
----------
Mary had a little lamb
whose fl33ce was white as sn0w
And everywhere that @Mary went
the 1amb was sure to go.

Output:

As mentioned in the question statement, the arrays are displayed in one row and three columns.

First row displays all the words of the file,

Second row displays the valid words (That have only letters).

Third row contains invalid words.


Related Solutions

simple Java project// please explain every statement with reasoning. Thank you Read from a file that...
simple Java project// please explain every statement with reasoning. Thank you Read from a file that contains a paragraph of words. Put all the words in an array, put the valid words (words that have only letters) in a second array, and put the invalid words in a third array. Sort the array of valid words using Selection Sort. Create a GUI to display the arrays using a GridLayout with one row and three columns. The input file Each line...
Please prove this and explain each step. Thank you. Use logical reasoning to solve the following...
Please prove this and explain each step. Thank you. Use logical reasoning to solve the following puzzle: Five friends disagree on whether to play video games or basketball. Either Alice or Bob, or both, want to play video games. Cindy and Don disagree on what they want to play. If Ellen plays video games, then so does Cindy. Alice and Don will play the same game. If Bob plays video games, then so do Alice and Ellen. Who is playing...
1. Is the following statement true or false? Explain your reasoning using graphs. “Every Giffen good...
1. Is the following statement true or false? Explain your reasoning using graphs. “Every Giffen good must be inferior, but not every inferior good exhibit the Giffen paradox.” 2. Using income and substitution effects, show that the size of the welfare loss caused by taxes will depend on how a tax is structured. Specifically, show (graphically) that taxes that are imposed on general purchasing power will have smaller welfare loss than will taxes imposed on a single commodity. (the Lump-Sum...
can you please explain each and every statement of the code without missing. it would be...
can you please explain each and every statement of the code without missing. it would be really helpful AVA PROJECT CREATING GUI WITH ARRAY Read from a file that contains a paragraph of words. Put all the words in an array, put the valid words (words that have only letters) in a second array, and put the invalid words in a third array. Sort the array of valid words using Selection Sort. Create a GUI to display the arrays using...
In Java please. Thank you! Recursion For this assignment you are going to write six different...
In Java please. Thank you! Recursion For this assignment you are going to write six different methods. Each method is to be written recursively. Any method that is written iteratively will not receive any credit, even if it is correct and produces the same results or output. You will be given a starter file. You are not allowed to change the signatures of any of the given methods. You are not allowed to add any methods to your solutions. Write...
Please, kindly explain ETIOLOGY OF HIV. Thank you
Please, kindly explain ETIOLOGY OF HIV. Thank you
Please include the problem number with every answer, thank you. During the month of October of...
Please include the problem number with every answer, thank you. During the month of October of the current year, Dan’s Accounting Service was opened. The following transactions occurred. Oct 1   Dan sold $70,000 worth of stock (50 shares) to start the business. Oct 1   Dan purchased $9,500 worth of office equipment on account from Keene’s             Furniture Supply. Oct 1   Dan paid October’s rent on the office. He wrote a check for $2,500. Oct 2   Dan purchased $400 worth of...
java 2D array / recursion explain every method You are requested to write a Java program...
java 2D array / recursion explain every method You are requested to write a Java program of a simple Memory Management Unit. The program should allow the following: 1. The user can create a process asking for memory. The program will return a process ID if the requested memory can be allocated. It will also print the allocated Base and Limit. 2. The user can delete a process by specifying a process ID. The program should do that and free...
Please I can get a flowchart and a pseudocode for this java code. Thank you //import...
Please I can get a flowchart and a pseudocode for this java code. Thank you //import the required classes import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BirthdayReminder {       public static void main(String[] args) throws IOException {        // declare the required variables String sName = null; String names[] = new String[10]; String birthDates[] = new String[10]; int count = 0; boolean flag = false; // to read values from the console BufferedReader dataIn = new BufferedReader(new...
Question: Can I get the code in Java for this assignment to compare? Please and thank you....
Question: Can I get the code in Java for this assignment to compare? Please and thank you. Can I get the code in Java for this assignment to compare? Please and thank you. Description Write a Java program to read data from a text file (file name given on command line), process the text file by performing the following: Print the total number of words in the file. Print the total number of unique words (case sensitive) in the file. Print...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT