Need Help! (Tokenizer error)

Hello,

i am currently ubdertaking an introduction to programming coarse and for one of my assignments i have been asked to create a program that will read read a file that contains the number 1-10 in this format;

1

2

3

4

5

6

7

8

9

10

The program must read these numbers, print them, find there sum then print the out put. i am completly lost, my program will compile yet i have an error while running it. java.util.NoSuchElementException please help.

here is my code.

import java.io.*;

import java.util.StringTokenizer;

//import java.util.NoSuchElementException;Tried Writting this in but still didnt work

publicclass addLine

{

publicstaticvoid main(String[] args)throws IOException, FileNotFoundException

{

int test1, test2, test3, test4,test5, test6, test7, test8, test9, test10;

int sumOfNum;

StringTokenizer tokenizer;

BufferedReader inFile =new

BufferedReader(new FileReader("test.txt"));

tokenizer =

new StringTokenizer(inFile.readLine());

test1 = Integer.parseInt(tokenizer.nextToken());

test2 = Integer.parseInt(tokenizer.nextToken());

test3 = Integer.parseInt(tokenizer.nextToken());

test4 = Integer.parseInt(tokenizer.nextToken());

test5 = Integer.parseInt(tokenizer.nextToken());

test6 = Integer.parseInt(tokenizer.nextToken());

test7 = Integer.parseInt(tokenizer.nextToken());

test8 = Integer.parseInt(tokenizer.nextToken());

test9 = Integer.parseInt(tokenizer.nextToken());

test10 = Integer.parseInt(tokenizer.nextToken());

System.out.println("Test scores: " + (test1) +" "

+ (test2) +" "

+ (test3) +" "

+ (test4) +" "

+ (test5) +" "

+ (test6) +" "

+ (test7) +" "

+ (test8) +" "

+ (test9) +" "

+ (test10));

sumOfNum = (test1 + test2 + test3 + test4 + test5+ test6 + test7 + test8+ test9 + test10);

System.out.println("Sum of all numbers: " + (sumOfNum));

inFile.close();

}

}

Thanks for the help

[3074 byte] By [Avida] at [2007-10-2 20:10:07]
# 1

A [url=http://java.sun.com/j2se/1.5.0/docs/api/java/util/StringTokenizer.html]StringTokenizer[/url] takes a String and splits it up into separate Strings. So if you gave it the String "1 2 3 4 5 6 7 8 9" it could be split apart with a StringTokenizer. But you don't have that. You have a String with the contents "1".

Take a look at the documentation for [url=http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedReader.html#readLine()]readLine()[/url] and you'll see that it does just that - it reads a single line of a text from a file.

So, instead of the code you have you'll want to do something a bit different. You'll want a loop of some sort that keeps reading the file until it gets a null. For each line you read you'll want to use the Integer.parse() method like you're doing now and do the appropriate math.

stdunbara at 2007-7-13 22:50:41 > top of Java-index,Developer Tools,Debugging and Profiling Tool APIs...