I am having trouble making a StringTokenizer break up a few lines of text into separate tokens. The inputted text is
3
monkeys
But, the StringTokenizer is apparently interpreting this as "3monkeys". I need it to be "3" and "monkeys". Because of this, a NumberFormatException is being throw since I need to convert the string "3" into an integer.
This is the code I have so far.
Scanner f = new Scanner( new FileInputStream("input.txt" )); // Yes, i have the actual input file path here, but I changed it for this question.
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
String temp = "";
//String cString = "";
while( f.hasNextLine() ) {
String cString = f.nextLine();
temp += cString;
}
StringTokenizer everythingTokens = new StringTokenizer( temp );
String[] everything = new String[ everythingTokens.countTokens() ];
for( int i = 0; i < everything.length; i++ ) {
everything[ i ] = everythingTokens.nextToken();
}
int numberOfPeople = Integer.parseInt( everything[ 0 ] ); // Line where exception occurs.
out.println( everything[ 0 ] );
The error message is this
Exception in thread "main" java.lang.NumberFormatException: For input string: "3monkeys"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at gift1.main(gift1.java:32)
Java Result: 1
Why is this happening and how can I fix it?