我正在尝试让扫描仪读取文本文件的输入,将该输入放入字符串,拥有该字符串的 StringTokenizer,然后拥有一个 String[],该数组的每个元素都是该 StringTokenizer 的令牌. 这样做的目的是从文本文件中获取输入文本的 String[],这样数组的每个元素都是文本文件中的一个单词。但是,到目前为止,我的代码会生成 NoSuchElementFound 异常。
Scanner f = new Scanner( "input.txt" ); // Yes, I have the file path here, I changed it though.
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt" );
String temp = "";
String cString = "";
while( ( cString = f.nextLine() ) != null ) { // Line where exception occurs
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();
}
out.println( everything[ 0 ] );
这是错误消息
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at gift1.main(gift1.java:21)
Java Result: 1
在文本文件中的输入是
Hey,
How are you?
为什么会发生这种情况,我该如何解决?