Question

I've previously completed a Java assignment where I wrote a program that reads a given text...

I've previously completed a Java assignment where I wrote a program that reads a given text file and creates an index that stores the line numbers for where individual words occur. I've been given a new assignment where I need to modify some of my old code.

I need to replace the indexer in my Index class with a NavigableMap<String, Word> and update my Word class with NavigableSet<Integer> lines. The instantiated objects should be TreeMap() and TreeSet(). I have below my code for those two classes, a test harness I was provided with, and a sample text file used for the assignment.

INDEXER CLASS

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Indexer
{
  
private List<Word> index;
private String fn;

public Indexer(String filename)
{
this.fn = filename;
index = new ArrayList<Word>();
}

public boolean index()
{
indexfile();
return true;
}

private void lineSplitter(String line, int lineno)
{
String[] words = null;
if (line.length() > 0) {
words = line.split("\\W+");
for (int i = 0; i < words.length; i++) {
boolean flag = false;
Word w = new Word(words[i]);
  
for (int j = 0; j < index.size(); j++) {
if (index.get(j).getWord().equals(w.getWord())) {
w = index.get(j);
w.addLine(lineno);
flag = true;
break;
}
}
  
if (!flag) {
w.addLine(lineno);
index.add(w);
}
}
}
}


private void indexfile()
{
try {
Scanner scan = new Scanner(new File(fn));
int count = 1;
String line;
while (scan.hasNextLine()) {
line = scan.nextLine();
lineSplitter(line, count);
count++;
}
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public List find(String w)
{
Word word = null;
for (int j = 0; j < index.size(); j++) {
if (index.get(j).getWord().equals(w)) {
word = index.get(j);
return word.getLines();
}
}
return null;
}

public void dumpList()
{
for (int i = 0; i < index.size(); i++) {
System.out.println(index.get(i).getWord() + " : " + index.get(i).getLines());
}
}
}

WORD CLASS

import java.util.ArrayList;
import java.util.List;

public class Word
{
private String w;
private List<Integer> lines;
  
public Word(String word)
{
this.w = word.toLowerCase();
lines = new ArrayList<Integer>();
}
  
public boolean addLine(int lineno)
{
if(!lines.contains(lineno)){
lines.add(lineno);
}   
return true;
}
  
public String getWord()
{
return w;
}
  
public List getLines()
{
return lines;
}
  
public boolean equals(Object obj)
{
if (this == obj)
return true;

if (obj == null || obj.getClass() != this.getClass())
return false;

Word word = (Word) obj;
return word.w.equals(this.w);
}
}

TEST HARNESS

public class PA5 {

    public static void main(String[] args) {

        Indexer idx = new Indexer(args[0]);

        boolean rc = idx.index();

        idx.dumpList();

   

        System.out.println("*****************");

        List<Integer> x = idx.find("PEACE");

        if ( x!= null)

            System.out.println(x);       

    }

}

SAMPLE TEXT

But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;

class Indexer {

        private NavigableMap<String, Word> wordMap;
        private String fn;

        public Indexer(String filename) {
                this.fn = filename;
                wordMap = new TreeMap<String, Word>();
        }

        public boolean index() {
                indexfile();
                return true;
        }

        private void lineSplitter(String line, int lineno) {
                String[] words = null;
                if (line.length() > 0) {
                        words = line.split("\\W+");
                        for (int i = 0; i < words.length; i++) {
                                
                                if(!wordMap.containsKey(words[i])) {
                                        wordMap.put(words[i], new Word(words[i]));
                                }
                                
                                wordMap.get(words[i]).addLine(lineno);
                        }
                }
        }

        private void indexfile() {
                try {
                        Scanner scan = new Scanner(new File(fn));
                        int count = 1;
                        String line;
                        while (scan.hasNextLine()) {
                                line = scan.nextLine();
                                lineSplitter(line, count);
                                count++;
                        }
                        scan.close();
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                }
        }

        public NavigableSet<Integer> find(String w) {
                if(wordMap.containsKey(w)) {
                        return wordMap.get(w).getLines();
                }
                return null;
        }

        public void dumpList() {
                for(String w: wordMap.keySet()) {
                        System.out.println(w + ": " + Arrays.toString(find(w).toArray()));
                }
        }
}

class Word {
        private String w;
        private NavigableSet<Integer> lines;

        public Word(String word) {
                this.w = word.toLowerCase();
                lines = new TreeSet<Integer>();
        }

        public boolean addLine(int lineno) {
                if (!lines.contains(lineno)) {
                        lines.add(lineno);
                }
                return true;
        }

        public String getWord() {
                return w;
        }

        public NavigableSet<Integer> getLines() {
                return lines;
        }

        public boolean equals(Object obj) {
                if (this == obj)
                        return true;

                if (obj == null || obj.getClass() != this.getClass())
                        return false;

                Word word = (Word) obj;
                return word.w.equals(this.w);
        }
}

public class PA5 {

        public static void main(String[] args) {

                Indexer idx = new Indexer(args[0]);

                idx.index();

                idx.dumpList();

                System.out.println("*****************");

                NavigableSet<Integer> x = idx.find("PEACE");

                if (x != null)
                        System.out.println(Arrays.toString(x.toArray()));

        }

}

please upvote.

Add a comment
Know the answer?
Add Answer to:
I've previously completed a Java assignment where I wrote a program that reads a given text...
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
  • PLEASE EDIT THE LAST 3 METHODS WHERE I PUT STARS AND DO WHAT THE COMMENTS SAY....

    PLEASE EDIT THE LAST 3 METHODS WHERE I PUT STARS AND DO WHAT THE COMMENTS SAY. THE CODE IS IN JAVA PROGRAMMING LANGUAGE. import java.util.AbstractList; import java.util.List; import java.util.RandomAccess; import java.lang.RuntimeException; import java.util.Arrays; public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess {    protected Object[] data; protected int size; public int size() {     return size; }    private void rangeCheck(int index) {     if (index < 0 || index >= size) throw new IndexOutOfBoundsException(""); }    @SuppressWarnings("unchecked") private E...

  • I have a Graph.java which I need to complete four methods in the java file: completeGraph(),...

    I have a Graph.java which I need to complete four methods in the java file: completeGraph(), valence(int vid), DFS(int start), and findPathBFS(int start, int end). I also have a JUnit test file GraphTest.java for you to check your code. Here is Graph.java: import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; /* Generic vertex class */ class Vertex<T> { public T data; public boolean visited; public Vertex() { data = null; visited = false; } public Vertex(T _data) { data =...

  • I have a program that reads a file and then creates objects from the contents of...

    I have a program that reads a file and then creates objects from the contents of the file. How can I create a linked list of objects and use it with the package class instead of creating and using an array of objects? I am not allowed to use any arrays of objects or any java.util. lists in this program. Runner class: import java.util.Scanner; import java.io.*; class Runner { public static Package[] readFile() { try { File f = new...

  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a...

    Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a string s as a parameter and returns true if the title of the string is equal to s. Create the same method for your library material copies. Note that it will need to be abstract in the LibraryMaterialCopy class MY CODE **************************************************************** LibraryCard: import java.util.List; import java.util.ArrayList; import java.time.LocalDate; import    java.time.temporal.ChronoUnit; public class LibraryCard {    private String id;    private String cardholderName;   ...

  • I need help with this. I need to create the hangman game using char arrays. I've...

    I need help with this. I need to create the hangman game using char arrays. I've been provided with the three following classes to complete it. I have no idea where to start. HELP!! 1. /** * This class contains all of the logic of the hangman game. * Carefully review the comments to see where you must insert * code. * */ public class HangmanGame { private final Integer MAX_GUESSES = 8; private static HangmanLexicon lexicon = new HangmanLexicon();...

  • Look for some finshing touches java help with this program. I just two more things added...

    Look for some finshing touches java help with this program. I just two more things added to this code. A loop at the end that will ask the user if they want to quit if they do want to quit the program stops if they don't it loads a new number sequence. import java.util.Random; import java.util.ArrayList; import java.util.Scanner; import java.util.Arrays; import java.util.List; import java.util.Collections; public class main { public static void main(String[] args) { List < Sequence > list =...

  • Modify the program that you wrote for the last exercise in a file named Baseball9.java that...

    Modify the program that you wrote for the last exercise in a file named Baseball9.java that uses the Player class stored within an array. The program should read data from the file baseball.txt for input. The Player class should once again be stored in a file named Player.java, however Baseball9.java is the only file that you need to modify for this assignment. Once all of the input data from the file is stored in the array, code and invoke a...

  • JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has...

    JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has you display a pessimistic poem from a list of phrases. Next, this program has you reverse the phrases to find another more optimistic poem. Use the following algorithm. 1.   You are given a list of phrases each ending with a pound sign: ‘#’. 2.   Create a single String object from this list. 3.   Then, split the String of phrases into an array of phrases...

  • Study the recursive instance method length()of MyLinkedList2 class and its associated auxiliary method. Then solve (a),...

    Study the recursive instance method length()of MyLinkedList2 class and its associated auxiliary method. Then solve (a), (b), and (c) below in a similar way: (a)   Convert the method public Element find(Object obj)of MyLinkedList2 class to a recursive one. Use an auxiliary private method. (b)   Convert the method public String toString( )of MyLinkedList2 class to a recursive one such that it returns the string representation of a linked list in the form: {ValueDatum1  valueDatum2 valueDatum3  . . .  valueDatumN-1   valueDatumN} Use an auxiliary private method....

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