我无法让StringTokenizer将几行文本分解成单独的标记。输入的文字是
3
monkeys
但是,StringTokenizer显然将其解释为“ 3monkeys”。我需要它是“ 3”和“ monkeys”。因此,由于我需要将字符串“ 3”转换为整数,因此引发了NumberFormatException。
这是我到目前为止的代码。
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
为什么会发生这种情况,我该如何解决?
最佳答案
当您通过temp += cString
将每行追加到字符串时,您拥有的是“ 3” +“ monkeys”,即“ 3 Monkeys”。您可以通过在每行之后添加一个空格来解决此问题; temp += cString + " "
。