Question

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

Homework Answers

Answer #1
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.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Using JAVA For this assignment, you will analyze code that uses a file input stream and...
Using JAVA For this assignment, you will analyze code that uses a file input stream and a file output stream. Read through the linked Java™ code. In a Microsoft® Word document, answer the following questions: Could this program be run as is? If not, what is it lacking? Does this program modify the contents of an input stream? In what way? What are the results of running this code? ********************************************** CODE TO ANALYZE  ******************************************************** /********************************************************************** *   Program:   Datasort *   Purpose:   ...
is there anything wrong with the solution. the question are from java course Write a main...
is there anything wrong with the solution. the question are from java course Write a main method that will request the user to enter Strings using a JOptionPane input dialog. The method should continue accepting strings until the user types “STOP”.       Then, using a JOptionPane message dialog, tell the user how many of the strings begin and end with a digit. Answer: import javax.swing.*; public class IsAllLetters {     public static void main(String[] args) {         String input;         int count =...
PLEASE USING C# TO SOLVE THIS PROBLEM. THANK YOU SO MUCH! a. Create a project with...
PLEASE USING C# TO SOLVE THIS PROBLEM. THANK YOU SO MUCH! a. Create a project with a Program class and write the following two methods (headers provided) as described below: - A Method, public static int InputValue(int min, int max), to input an integer number that is between (inclusive) the range of a lower bound and an upper bound. The method should accept the lower bound and the upper bound as two parameters and allow users to re-enter the number...
I need this before the end of the day please :) In Java 10.13 Lab 10...
I need this before the end of the day please :) In Java 10.13 Lab 10 Lab 10 This program reads times of runners in a race from a file and puts them into an array. It then displays how many people ran the race, it lists all of the times, and if finds the average time and the fastest time. In BlueJ create a project called Lab10 Create a class called Main Delete what is in the class you...
You will write a program that loops until the user selects 0 to exit. In the...
You will write a program that loops until the user selects 0 to exit. In the loop the user interactively selects a menu choice to compress or decompress a file. There are three menu options: Option 0: allows the user to exit the program. Option 1: allows the user to compress the specified input file and store the result in an output file. Option 2: allows the user to decompress the specified input file and store the result in an...
Project 2 statement Please write this in JAVA. Please read this entire statement carefully before you...
Project 2 statement Please write this in JAVA. Please read this entire statement carefully before you start doing anything… This project involves implementing a simple university personnel management program. The program contains two different kinds of objects: students and faculty. For each object, the program stores relevant information such as university ID, name, etc. Different information is stored depending on the type of the object. For example, a student has a GPA, while a faculty has a title and department...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT