Cpt.Awesome
Cpt.Awesome

Reputation: 65

orderedlinkedlist JAVA counting words in .txt file no duplicate words plus counter>

Okay this program is supposed to count the number of times each word shows up in a .txt file I'm on the right track because this program shows every word in the file in a text area but I need it to not repeat words and increment a counter instead. Am I on the right track under the for each word:words statement? It's in an ordered linked list so the words are in order alphabetically...

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;


public class Oct29 extends JPanel
{
  private OrderedList<String> words;
  private String filename;
  private int width = 800;
  private int height = 600;
  private TextArea textarea;

  public Oct29()
  {
    Scanner scan;
    textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
    textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
    textarea.setPreferredSize(new Dimension(width,height));
    setPreferredSize(new Dimension(width,height));
    add(textarea);
    JFileChooser chooser = new JFileChooser("../Text");
    int returnvalue = chooser.showOpenDialog(null);

    if(returnvalue == JFileChooser.APPROVE_OPTION)
    {
      try
      {
        File file = chooser.getSelectedFile();
        filename = file.getName();
        System.err.println(filename);
        scan = new Scanner(file);
      }
      catch (IOException e)
      {
        System.err.println("IO EXCEPTION");
        return;
      }       
    }
    else
    {
      return;
    }
    words = new OrderedLinkedList<String>();
    while(scan.hasNext())
    {
      String token = scan.next().toLowerCase();
      token = token.replace(",","").replace(".","");
      words.add(token);
    }
    scan.close();
    textarea.append("    "+filename+" has wordcount: "+words.size()+
      "\n-------------------------\n\n");

     for(String word : words)
     {     
        textarea.append(word+"\n");  // instead of displaying each word I need it to read when the word changes and then list a count of that word...
     }
  }

  public static void main(String[] arg)
  {
    JFrame frame = new JFrame("Oct 29");
    frame.getContentPane().add(new Oct29());
    frame.pack();
    frame.setVisible(true);
  }
}

Upvotes: 0

Views: 165

Answers (1)

natus
natus

Reputation: 74

There are two ways you can go about this

1) As you are reading them in keep a counter for each word and then when you output this you can output the counter

2) As you are outputting keep a counter and when the word changes then you output the counter and the word and then set the counter back to zero.

You can start by in your for loop using String.equals. Then if this is true, increment. If its false then do whatever you need (assign the value somewhere or just output it) and then set the counter to 0.

Upvotes: 1

Related Questions