Question

In: Computer Science

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 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 of the input file would be:

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

Submitting the Project.

You should have two files to submit for this project:

Project1.java

WordGUI.java





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

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 {
      file = new File("input.txt");
      fr = new FileReader(file);
      br = new BufferedReader(fr);
      numberOfWordsInFile = 22;
      words = new String[numberOfWordsInFile];
      index = 0;
      while ((line = br.readLine()) != null) {
        st = new StringTokenizer(line);
        while (st.hasMoreElements()) {
          words[index] = (String) st.nextElement();
          index++;
        }
      }
      fr.close();
      validWords = new String[numberOfWordsInFile];
      validWordsIndex = 0;
      invalidWords = new String[numberOfWordsInFile];
      invalidWordsIndex = 0;
      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++;
      }
      selectionSort(validWords, validWordsIndex);
      WordGUI wg = new WordGUI();
      wg.display(
        words,
        index,
        validWords,
        validWordsIndex,
        invalidWords,
        invalidWordsIndex
      );
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  static String[] selectionSort(String[] validWords, int validWordsIndex) {
    for (int i = 0; i < validWordsIndex - 1; i++) {
      int min_index = i;
      String minStr = validWords[i];
      for (int j = i + 1; j < validWordsIndex; j++) {
        if (validWords[j].compareTo(minStr) < 0) {
          minStr = validWords[j];
          min_index = j;
        }
      }
      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;

class WordGUI {

  public void display(
    String[] words,
    int index,
    String[] validWords,
    int validWordsIndex,
    String[] invalidWords,
    int invalidWordsIndex
  ) {
    JFrame f = new JFrame();
    f.setLayout(new GridLayout(1, 3));

    String label = "";

    label = convertArrayToLabel(words, index);
    f.add(new JLabel(label));

    label = convertArrayToLabel(validWords, validWordsIndex);
    f.add(new JLabel(label));

    label = convertArrayToLabel(invalidWords, invalidWordsIndex);
    f.add(new JLabel(label));

    f.setSize(1000, 1000);
    f.setVisible(true);
  }

  public String convertArrayToLabel(String[] array, int maxIndex) {
    String label = "

"; for (int i = 0; i < maxIndex; i++) { label = label + array[i] + "
"; } label = label + "

"; return label; } }

Solutions

Expert Solution

file-name:  Project1.java
---------------------------------------
/*
importing all necessary classes
 */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

class Project1 {

    /*
    main( ) method
     */
    public static void main(String args[]) {

        // creating a new File object
        File file = null;
        // creating a FileReader object, to read the contents of file.
        FileReader fr = null;
        // Creating BufferedReader object.
        BufferedReader br = null;
        // 'line' is a String variable , it stores each line in the paragraph line by line.
        String line;
        // StringTokenizer, this is used to break a string into tokens
        StringTokenizer st = null;
        // this variable represents the number of words in file
        int numberOfWordsInFile;

        // This array stores all the words ( valid and invalid )
        // Here we only did array initialization
        String words[];
        int index;

        // array of valid words ( words that only have letters )
        // Here we only did array initialization
        String validWords[];
        int validWordsIndex;

        // This array stores all the invalid words.
        // Here we only did array initialization
        String invalidWords[];
        int invalidWordsIndex;

        // This try block is used for Exceptional handling purpose
        // FileNotFoundException and IoException

        try {

            file = new File("input.txt");
            fr = new FileReader(file);
            br = new BufferedReader(fr);

            numberOfWordsInFile = 22;
            /*
            Here you are creating an array object, that has size of 22. It means it can only store 22 words.

            But instead of array, we can use dynamic arrays ( ArrayList ). ( Just suggesting )
             */
            words = new String[numberOfWordsInFile];
            index = 0;

            // while loop
            // checking if the line we read is null or not.
            while ((line = br.readLine()) != null) {
                /*
                this has default delimiters like new line, space, tab, carriage return .
                divides the string into multiple tokens and stores in word array.
                 */
                st = new StringTokenizer(line);
                while (st.hasMoreElements()) {
                    words[index] = (String) st.nextElement();
                    index++;
                }
            } // END OF WHILE LOOP
            // closing the file.
            fr.close();

            // creating validwords array object of size 22
            validWords = new String[numberOfWordsInFile];
            validWordsIndex = 0;
            // creating invalidwords object of size 22
            invalidWords = new String[numberOfWordsInFile];
            invalidWordsIndex = 0;

            /*
            Classifying the words into valid and invalid words
             */
            for (int i = 0; i < words.length; i++) {

                // if word is not a null, and only has alphabets.
                if (
                        (words[i] != null) &&
                        (words[i].matches("^[a-zA-Z]*$"))
                ) {
                    validWords[validWordsIndex] = words[i];
                    validWordsIndex++;
                } else {
                    invalidWords[invalidWordsIndex] = words[i];
                    invalidWordsIndex++;
                }
            } // end of for loop

            // calling selection sort method.
            validWords = selectionSort(validWords, validWordsIndex);

            // creating a WordGUI object.
            WordGUI wg = new WordGUI();

            // calling the display method inside wordGUI, and
            // passing words, invalid words and valid words and their count as arguments
            wg.display(
                    words,
                    index,
                    validWords,
                    validWordsIndex,
                    invalidWords,
                    invalidWordsIndex
            );
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This selection sort method takes , string array of valid words and no.of valid words as arguments.
     * We sort the array using selection sort mechanism,and return a sorted string array.
     * @param validWords
     * @param validWordsIndex
     * @return sorted string array.
     */
    public static String[] selectionSort(String[] validWords, int validWordsIndex) {
        for (int i = 0; i < validWordsIndex - 1; i++) {
            int min_index = i;
            String minStr = validWords[i];
            for (int j = i + 1; j < validWordsIndex; j++) {
                if (validWords[j].compareTo(minStr) < 0) {
                    minStr = validWords[j];
                    min_index = j;
                }
            }
            if (min_index != i) {
                String temp = validWords[min_index];
                validWords[min_index] = validWords[i];
                validWords[i] = temp;
            }
        }
        return validWords;
    }
}

====================================================================

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

class WordGUI {

    public void display(
            String[] words,
            int index,
            String[] validWords,
            int validWordsIndex,
            String[] invalidWords,
            int invalidWordsIndex
    ) {
        // Creating a Java frame object.
        // This acts like a container.
        JFrame f = new JFrame();
        // GridLayout represents a layout manager with 1 row and 3 columns.
        f.setLayout(new GridLayout(1, 3));

        String label = "";

        /*
        JLabel is a component , which contains some text in it.
         */
        /*
         * This convertArrayToLabel method takes array and no.of elements as input
         * arguments and returns a String. It arranges the elements of array in a neat, readable order.
         * and we give that label as text to Jlablel.
         */
        label = convertArrayToLabel(words, index);
        // adds label to the container. JFrame
        f.add(new JLabel(label));

        // We are creating a JLabel of valid words.
        label = convertArrayToLabel(validWords, validWordsIndex);
        // adds label to the container. JFrame
        f.add(new JLabel(label));

        // We are creating a JLabel of invalid words.
        label = convertArrayToLabel(invalidWords, invalidWordsIndex);
        // adds label to the container. JFrame
        f.add(new JLabel(label));

        //creating a window of this size.
        f.setSize(1000, 1000);
        // this blocks the window from closing and it will be displayed until we close it.
        f.setVisible(true);
    }

    // this method takes String array as argument and arranges the array elements in nice format.
    public String convertArrayToLabel(String[] array, int maxIndex) {
        String label = "";
        for (int i = 0; i < maxIndex; i++) {
            label = label + array[i] + " ";
        }
        label = label + " ";
        return label;
    }
}

==================================================

OUTPUT:

output I got for the sample input.

The below is the input file I used.

pizza burger biryani chole bature aggi chicken65 burger14  1234 aalu panner
john24 ramesh kiran12 somu13 karan ravana sushant rajput13 ravi

Hey If you have any doubt please ask in comment section. Please Upvote if you like my effort. THANK YOU!!


Related Solutions

Can you list every account you can think of that would go on a Statement of...
Can you list every account you can think of that would go on a Statement of Cash Flows and where It goes on a Statement of Cash Flows?
Python 3 can you explain what every single line of code does in simple terms please...
Python 3 can you explain what every single line of code does in simple terms please so basically # every single line with an explanation thanks def longest(string): start = 0;end = 1;i = 0; while i<len(string): j = i+1 while j<len(string) and string[j]>string[j-1]: j+=1 if end-start<j-i: end = j start = i i = j; avg = 0 for i in string[start:end]: avg+=int(i) print('The longest string in ascending order is',string[start:end]) print('The average is',avg/(end-start)) s = input('Enter a string ')...
Can you please explain in detail what each line of code stands for in the Main...
Can you please explain in detail what each line of code stands for in the Main method import java.util.Scanner; public class CashRegister { private static Scanner scanner = new Scanner(System.in); private static int dollarBills[] = {1, 2, 5, 10, 20, 50, 100}; private static int cents[] = {25, 10, 5, 1}; public static void main(String[] args) { double totalAmount = 0; int count = 0; for (int i = 0; i < dollarBills.length; i++) { count = getBillCount("How many $"...
C#: If the code is the only thing that you can provide without the pictures of...
C#: If the code is the only thing that you can provide without the pictures of the form, then that is fine as well. Topics: hiding/showing controls, StatusStrip, custom event arguments, radio buttons Students will create an application that uses a dialog to create a spaceship object to populate a ListView. This ListView will be able to display in either large or small icon mode using a menu option to switch between them. Selecting a spaceship in the ListView will...
PYTHON PLEASE!! ALSO: if you can include an explanation of what the code means that would...
PYTHON PLEASE!! ALSO: if you can include an explanation of what the code means that would be appreciated 8.19 LAB*: Program: Soccer team roster (Dictionaries) This program will store roster and rating information for a soccer team. Coaches rate players during tryouts to ensure a balanced team. (1) Prompt the user to input five pairs of numbers: A player's jersey number (0 - 99) and the player's rating (1 - 9). Store the jersey numbers and the ratings in a...
Explain the following statement: ‘Life as we know it, would not exist without bacteria’ as it...
Explain the following statement: ‘Life as we know it, would not exist without bacteria’ as it relates to the oxygen revolution, endosymbiosis, and nitrogen fixation.
Without using formulas, explain how you can determine each of the following: c. If you have...
Without using formulas, explain how you can determine each of the following: c. If you have 10 people, how many different committees of 3 people can be formed for the offices of president, vice-president, and secretary? d. Does order matter or not for part c? Explain.
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...
1. Please explain why you would or would not think each of the following variables to...
1. Please explain why you would or would not think each of the following variables to be normally distributed. [Hint: For normally distributed variable, most of the data are around the middle value and frequency of observations keeps falling as you move away from the middle in both directions]. a. Retirement age of the U.S workers. b. Household income in the U.S. in 2018. c. Height of U.S. adults in 2018. d. Birthweight of girls in the U.S. in 2018....
Can you have TSS without turbidity? Can you have turbidity without TSS? Explain why based on...
Can you have TSS without turbidity? Can you have turbidity without TSS? Explain why based on the physics of the measurement.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT