views:

53

answers:

1

I have a .txt file with integers on each line e.g.

1
4
5
6

I want to count the occurences of the values that are in an array with the file.

My code extract is this

    String s = null;
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    while ((s = br.readLine()) !=null) {
    StringTokenizer st = new StringTokenizer(s);
    while (st.hasMoreTokens()) {
    for (int i = 0; i < array.length; i++) {
    if (st.nextToken().equals(array[i])) {
    count++;
        }
Error Messages are java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(Unknown Source)

The file is in the same directory.

Could someone please give me a hand? Thanks

+2  A: 

Your problem is that you're trying to pull a new token for every iteration of the for loop - instead, you need to assign the result of st.nextToken() to a variable before the for loop, and then use that variable in the if statement.

String s = null;
String token = null;
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while ((s = br.readLine()) !=null) {
    StringTokenizer st = new StringTokenizer(s);
    while (st.hasMoreTokens()) {
        token = st.nextToken();
        for (int i = 0; i < array.length; i++) {
            if (token.equals(array[i])) {
                count++;
            }
        }
    }
}
Amber
Thank you for your time and help.