Question

PLEASE HELP IN JAVA: This is an exercise in using the java LinkedList class. Using input...

PLEASE HELP IN JAVA:

This is an exercise in using the java LinkedList class.

Using input file words.txt , create a LinkedList BUT you must NOT add a word that is already in the list and you MUST add them in the order received to the end of the list.

For example, if your input was cat, cat, dog, mouse, dog, horse

your list would now contain cat, dog, mouse, horse. And the head of the list would be cat, and the tail would be horse. Note: it is NOT sorted.

This list represents a code, and the code for one word is the next word in the list. So the code for cat is dog and the code for mouse is horse, and the code for horse is cat(go round to the head of the list).

Now ask your user for a phrase (input from the keyboard) and output the coded phrase. In the above example if the input was "mouse cat" the output would be "horse dog".

How do you know if you have the correct output? I suggest you make your own (small) input file so you can test it.

Rubric:

* use of try/catch

*use of while loop to collect inout

* no duplicates put into list

* prompt user for phrase

* code the phrase

* correct output

words.txt (around 1000 words)

noncollectable

reallocation

drenching

obnoxious

venality

dybbuk

shotgun

changelessly

handiwork

unheralded

dovecote

anode

spellbind

psychologist

improvisational

prejudiced

apply

pokey

secular

masterfully

at

overdrawn

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts. Thanks

// LinkedList.java

public class LinkedList {

      // pointers to head and tail

      private Node head;

      private Node tail;

      private int size;// number of words

      /**

      * default constructor

      */

      public LinkedList() {

            head = null;

            tail = null;

            size = 0;

      }

      /**

      * @return true if the list is empty

      */

      public boolean isEmpty() {

            return size == 0;

      }

      /**

      * return true if a given word exists in the linked list, otherwise false

      *

      * @param word

      *            - word to be checked (case sensitive)

      */

      public boolean contains(String word) {

            Node node = head;

            // looping through the list to check if the word existss

            while (node != null) {

                  if (node.getWord().equals(word)) {

                        return true;

                  }

                  node = node.getNext();

            }

            return false;

      }

      /**

      * method to add a word to the list

      */

      public void add(String word) {

            // adding the word only if it is not already added

            if (!contains(word)) {

                  Node newNode = new Node(word);

                  if (isEmpty()) {

                        // adding as first node

                        head = newNode;

                        tail = newNode;

                  } else {

                        // adding at the tail

                        tail.setNext(newNode);

                        tail = newNode;

                  }

                  size++;

            }

      }

      /**

      * method to find the code of a word in the list

      *

      * @param word

      *            - original word

      * @return the next word of the given word in the list, will return head

      *         node's data if the word is at the tail, or return the word

      *         unchanged if it is not found in the list

      */

      public String getCode(String word) {

            Node temp = head;

            while (temp != null) {

                  if (temp.getWord().equals(word)) {

                        // found the word, getting next word

                        if (temp.getNext() == null) {

                              // no next node, so returning head node's data

                              return head.getWord();

                        } else {

                              // returning word at next position

                              return temp.getNext().getWord();

                        }

                  }

                  temp = temp.getNext();

            }

            // not found, returning word unchanged

            return word;

      }

      @Override

      public String toString() {

            // returning a String representation of the list

            String data = "[";

            Node temp = head;

            for (int i = 0; i < size; i++) {

                  data += temp.getWord();

                  if (i != size - 1) {

                        data += ", ";

                  }

                  temp = temp.getNext();

            }

            data += "]";

            return data;

      }

      /**

      * private inner class to represent a Node, must be placed within

      * LinkedList.java (inside LinkedList class)

      */

      private class Node {

            String word;

            Node next;

            public Node(String word) {

                  this.word = word;

            }

            public void setNext(Node next) {

                  this.next = next;

            }

            public Node getNext() {

                  return next;

            }

            public void setWord(String word) {

                  this.word = word;

            }

            public String getWord() {

                  return word;

            }

      }

}

// Main.java (with main method)

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class Main {

      // method to load words from a file, fill a linked list and return it

      static LinkedList loadWords(String fileName) throws FileNotFoundException {

            LinkedList wordsList = new LinkedList();

            Scanner scanner = new Scanner(new File(fileName));

            while (scanner.hasNext()) {

                  String word = scanner.nextLine();

                  wordsList.add(word);

            }

            return wordsList;

      }

      public static void main(String[] args) {

            Scanner inScanner = new Scanner(System.in); //user input scanner

            Scanner textScanner; // to scan individual words in the input text sequence

            String input = "";

            try {

                  //loading words from file

                  LinkedList wordsList = loadWords("words.txt");

                  //displaying loaded words, for debugging. remove it if you want

                  System.out.println("Loaded words: " + wordsList);

                  //looping until user quits

                  while (!input.equalsIgnoreCase("quit")) {

                        System.out.print("Enter a phrase (or 'quit' to end): ");

                        input = inScanner.nextLine();

                        if (!input.equalsIgnoreCase("quit")) {

                              //iterating through input phrase

                              textScanner = new Scanner(input);

                              System.out.print("Code: ");

                              //displaying the code for each words

                              while (textScanner.hasNext()) {

                                    String word = textScanner.next();

                                    System.out.print(wordsList.getCode(word) + " ");

                              }

                              System.out.println();

                        }

                  }

            } catch (FileNotFoundException e) {

                  //words.txt file not found, must be there in the same directory

                  e.printStackTrace();

            }

      }

}

//OUTPUT

Loaded words: [noncollectable, reallocation, drenching, obnoxious, venality, dybbuk, shotgun, changelessly, handiwork, unheralded, dovecote, anode, spellbind, psychologist, improvisational, prejudiced, apply, pokey, secular, masterfully, at, overdrawn]

Enter a phrase (or 'quit' to end): noncollectable shotgun

Code: reallocation changelessly

Enter a phrase (or 'quit' to end): masterfully overdrawn

Code: at noncollectable

Enter a phrase (or 'quit' to end): dybbuk someunknowntext

Code: shotgun someunknowntext

Enter a phrase (or 'quit' to end): quit

Add a comment
Know the answer?
Add Answer to:
PLEASE HELP IN JAVA: This is an exercise in using the java LinkedList class. Using input...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a program that first reads in the name of an input file and then reads the file using the csv.reader() method.

     Write a program that first reads in the name of an input file and then reads the file using the csv.reader() method. The file contains a list of words separated by commas. Your program should output the words and their frequencies (the number of times each word appears in the file) without any duplicates. Ex: If the input is: inputl.csv and the contents of input1.csv are: hello, cat, man, hey, dog, boy, Hello, man, cat, woman, dog, Cat, hey, boy the output is: hello 1 cat 2 man...

  • JAVA Write Java code for extending the LinkedList class of java.util.* to ExtLinkedList that would include...

    JAVA Write Java code for extending the LinkedList class of java.util.* to ExtLinkedList that would include the following method: public ExtLinkedList firstHalfList() which returns the first half of the list. In other words, if you have a ExtLinkedList of size 5, for example, the method firstHalfList should return the list with the first two nodes. If it is a list of size 6, it should return the list with the first three nodes. The original list should not be modified....

  • //LinkedList import java.util.Scanner; public class PoD {    public static void main( String [] args )...

    //LinkedList import java.util.Scanner; public class PoD {    public static void main( String [] args ) { Scanner in = new Scanner( System.in ); LinkedList teamList = new LinkedList(); final int TEAM_SIZE = Integer.valueOf(in.nextLine()); for (int i=0; i<TEAM_SIZE; i++) { String newTeamMember = in.nextLine(); teamList.append(newTeamMember); } while (in.hasNext()) { String removeMember = in.nextLine(); teamList.remove(removeMember); }    System.out.println("FINAL TEAM:"); System.out.println(teamList); in.close(); System.out.print("END OF OUTPUT"); } } =========================================================================================== //PoD import java.util.NoSuchElementException; /** * A listnked list is a sequence of nodes with...

  • JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList...

    JAVA you have been given the code for Node Class (that holds Strings) and the LinkedList Class (some methods included). Remember, you will use the LinkedList Class that we developed in class not Java’s LinkedList Class. You will add the following method to the LinkedList Class: printEvenNodes – this is a void method that prints Nodes that have even indices (e.g., 0, 2, 4, etc). Create a LinkedListDemo class. Use a Scanner Class to read in city names and store...

  • **********Using Java*************** Create 5 CLASSES: Driver(main), Word, AnagramFamily, and 2 Comparators classes words.txt is a very...

    **********Using Java*************** Create 5 CLASSES: Driver(main), Word, AnagramFamily, and 2 Comparators classes words.txt is a very large file containing thousands of words. I will post some words down below. some of word.txt aa aah aahed aahing aahs aal aalii aaliis aals aardvark aardvarks aardwolf aardwolves aargh aarrgh aarrghh aas aasvogel aasvogels ab aba abaca abacas abaci aback abacterial abacus abacuses abaft abaka abakas abalone abalones abamp abampere abamperes abamps abandon abandoned abandoner abandoners abandoning abandonment abandonments abandons abapical abas abase...

  • JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class....

    JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class. Print out the results after testing each of the methods in both of the classes and solving a simple problem with them. Task 1 – ArrayList Class Create an ArrayList class. This is a class that uses an internal array, but manipulates the array so that the array can be dynamically changed. This class should contain a default and overloaded constructor, where the default...

  • I need help writing this code for java class. Starter file: Project3.java and input file: dictionary.txt...

    I need help writing this code for java class. Starter file: Project3.java and input file: dictionary.txt Project#3 is an extension of the concepts and tasks of Lab#3. You will again read the dictionary file and resize the array as needed to store the words. Project#3 will require you to update a frequency counter of word lengths every time a word is read from the dictionary into the wordList. When your program is finished this histogram array will contain the following:...

  • You will write three static methods to manipulate an input String in different ways using various...

    You will write three static methods to manipulate an input String in different ways using various String methods. You need to provide the code for each of the three static methods in class StringPlay (requirements for each listed below). You will also change the control statement in the test harness to allow for variations in the sentinel value. You need to modify the loop control condition in Lab09.java so that user inputs of ‘finish’, “FINISH”, “FiniSH”, “fINISH”, etc. will end...

  • For the LinkedList class, create a getter and setter for the private member 'name', constructing your...

    For the LinkedList class, create a getter and setter for the private member 'name', constructing your definitions based upon the following declarations respectively: std::string get_name() const; and void set_name(std::string); In the Main.cpp file, let's test your getter and setter for the LinkedLIst private member 'name'. In the main function, add the following lines of code: cout << ll.get_name() << endl; ll.make_test_list(); ll.set_name("My List"); cout << ll.get_name() << endl; Output should be: Test List My List Compile and run your code;...

  • a Java code Complete the provided code by adding a method named sum() to the LinkedList...

    a Java code Complete the provided code by adding a method named sum() to the LinkedList class. The sum() method should calculate the sum of all of the positive numbers stored in the linked list. The input format is the number of items in the list, followed by each of the items, all separated by spaces. Construction of the linked list is provided in the template below. The output should print the sum of the positive values in the list....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT