2

単純なテキスト ファイルからの読み取りに問題があり、その理由がわかりません。以前にこれを行ったことがありますが、何が問題なのかわかりません。どんな助けでも大歓迎です!

import java.io.File;
import java.util.Scanner;

public class CS2110TokenReader {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        File theFile = new File("data1.txt");
        Scanner scnFile = new Scanner(theFile);

        try {
            scnFile = new Scanner(theFile);
        } catch (Exception e) {
            System.exit(1);
        }
        while (theFile.hasNext()) {
            String s1 = theFile.next();
            Double d1 = theFile.nextDouble();

            System.out.println(s1 + "   " + d1);
        }

    }

}

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The method hasNext() is undefined for the type File
    The method next() is undefined for the type File
    The method nextDouble() is undefined for the type File

    at CS2110TokenReader.main(CS2110TokenReader.java:20)

次の行をスキャンすることすらできません。それが私の目標です。スキャンして読むこと。

4

1 に答える 1

6
while (theFile.hasNext()) {  // change to `scnFile.hasNext()`
    String s1 = theFile.next();  // change to `scnFile.next()`
    Double d1 = theFile.nextDouble();  // change to `scnFile.nextDouble()`

    System.out.println(s1 + "   " + d1);
}

Scanner参照時にクラスのメソッドを呼び出していFileます。すべての呼び出しでtheFile置き換えます。scnFile

next()第 2 に、 andを呼び出してnextDouble()いますが、チェックはhasNext()1 回だけです。NoSuchElementExceptionそれはある時点であなたを投げるかもしれません。実際に読む前に、読む入力があることを確認してください。

于 2013-01-24T19:27:09.660 に答える