我无法让 StringTokenizer 将几行文本分解为单独的标记。输入的文字是
3
monkeys
但是,StringTokenizer 显然将其解释为“3monkeys”。我需要它是“3”和“猴子”。正因为如此,一个 NumberFormatException 被抛出,因为我需要将字符串“3”转换为一个整数。
这是我到目前为止的代码。
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 ] );
错误信息是这样的
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
为什么会发生这种情况,我该如何解决?