All pastes #902638 Raw Edit

Unnamed

public java v1 · immutable
·published 2008-02-13 17:36 UTC
rendered paste body
import java.util.ArrayList;public class Lab05 {	public static void main(String [] args)	{	  String[] strings = createStringArray();	  ArrayList words = stringsToWords(strings);	  printWordList(words);	  System.out.println("Average word length: " + averageWordLength(words));		System.out.println("\nEnd of processing.");	}	public static String[] createStringArray() {	  // Unusual construction! See the course notes for an example.	  return new String[] {	    "O my Luve's like a red, red rose, That's newly sprung in June.",	    "O my Luve's like the melodie, That's sweetly play'd in tune.",	    "As fair art thou, my bonie lass, So deep in luve",	    "am I; And I will luve thee still, my dear, Till a' the seas gang dry."	  };	}	public static ArrayList stringsToWords(String[] s) {	  ArrayList result = new ArrayList();	  Word w;	  String[] tokens;	  for (int i = 0; i < s.length; i++) {	    tokens = s[i].split("\\s+");	    for (int j = 0; j < tokens.length; j++) {	      w = findWord(result, tokens[j]);	      if (w == null)	        result.add(new Word(tokens[j]));	      else	      	System.out.println("you should add something here to add the frequency by one.");	      }	  }	  return result;	}  // Exercise 1: linear search for a word in the array list  public static Word findWord(ArrayList words, String word) {	  for (int i = 0; i < words.size(); i++) {		//quite confused here... 		  if ( ((Word)(words.get(i))).compare()  ) return words(i);	  }    return null;  }	public static void printWordList(ArrayList words) {	  for (int i = 0; i < words.size(); i++)	    System.out.println(words.get(i));	}	public static double averageWordLength(ArrayList words) {	  int total = 0;	  for (int i = 0; i < words.size(); i++) {	    // Exercise #2: This doesn't work - fix it!	    // total += words.get(i).countLetters();	  }	  return (double)total / words.size();	}}class Word {	private String word;	private int frequency;	public Word(String w) {	  word = w;	  frequency = 1;	}	public void addFreq () {		frequency++;	}		//Not familiar enough to understand here... 	public boolean compare () {		if ( this.word == word ) { return true; }		return false;	}	public int countCharacters() {	  return word.length();	}  // Exercise 1: Add methods to this class	public int countLetters() {	  int count = 0;	  for (int i = 0; i < word.length(); i++) {	    if (Character.isLetter(word.charAt(i)))	      count++;	  }	  return count;	}	public String toString() {		return "Word: '" + word + "' frequency: " + frequency +		       " length: " + countLetters();	}}