2

我正在尝试让扫描仪读取文本文件的输入,将该输入放入字符串,拥有该字符串的 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?

为什么会发生这种情况,我该如何解决?

4

2 回答 2

2

这不是您使用扫描仪的方式。你会这样做:

while (scanner.hasNextLine()) {
   String line = scanner.nextLine();
   // work with your line here
}

Please have a look at the Scanner API and you'll see that it doesn't return null if it runs out of lines. Instead it throws a .... NoSuchElementException. I think that you're confusing its use with that of a BufferedReader, and they're really two completely distinct species.

于 2012-07-23T00:38:29.777 回答
1

Change to this --

while( f.hasNextLine() ) {
    cString = f.nextLine();
    temp += cString;
}
于 2012-07-23T00:39:10.300 回答