- #1
prosteve037
- 110
- 3
Homework Statement
I have to define part of a method that will take in a String, segment the input into words, keep track of how many of each word there are in the string, and then return a HashMap<String, Integer> that shows how many of each word there are in the string.
A separate helper class named CharacterFromFileReader "reads" the String, character-by-character, and can iterate through the string. Here's its definition:
Code:
package util.general;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
public class CharacterFromFileReader implements Iterator<Character> {
private final static int EOF_VALUE = -1;
private FileReader inputStream;
private int lastRead;
public CharacterFromFileReader(String path) {
try {
inputStream = new FileReader(path);
read();
} catch (FileNotFoundException e) {
e.printStackTrace();
finish();
}
}
private void finish() {
lastRead = EOF_VALUE;
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void read() {
try {
lastRead = inputStream.read();
} catch (IOException e) {
finish();
}
}
@Override
public boolean hasNext() {
return lastRead != EOF_VALUE;
}
@Override
public Character next() {
char c = (char) lastRead;
read();
return c;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
Homework Equations
-----------------------------------------------------------------------
The Attempt at a Solution
Here's the code I've written so far and am confident with:
Code:
package hw3;
import java.util.HashMap;
import util.general.CharacterFromFileReader;
public class Homework3Class {
public Homework3Class() {}
public HashMap<String, Integer> wordCounter(String inputPath) {
HashMap<String, Integer> hm = new HashMap<String, Integer>();
CharacterFromFileReader cffr = new CharacterFromFileReader(inputPath);
String s = new String();
while(cffr.hasNext()) {
char c = cffr.next();
if (this.characterChecker(c)) {
.
.
.
}
else if (this.characterChecker(c) == false) {
s = new String();
}
}
return hm;
}
public boolean characterChecker(char c) {
if (c != ' ' && c != '\t' && c != '\n' && c != ',' && c != '.') {
return true;
}
else {
return false;
}
}
}
Not much at all so far :P
I was thinking that in the dotted space there should be code that takes the character stored in reference c and adds it to the string s... I just don't know how :/