2

次のようなテキストファイルがあります。

Description|SKU|Retail Price|Discount
Tassimo T46 Home Brewing System|43-0439-6|17999|0.30
Moto Precise Fit Rear Wiper Blade|0210919|799|0.0

すべてを読み取ることができるようになっています。最初の行を読み取るという事実を除けば、完全に機能します。これは、.txtファイルの一種の凡例であり、無視する必要があります。

public static List<Item> read(File file) throws ApplicationException {
    Scanner scanner = null;
    try {
        scanner = new Scanner(file);
    } catch (FileNotFoundException e) {
        throw new ApplicationException(e);
    }

    List<Item> items = new ArrayList<Item>();

    try {
        while (scanner.hasNext()) {
            String row = scanner.nextLine();
            String[] elements = row.split("\\|");
            if (elements.length != 4) {
                throw new ApplicationException(String.format(
                        "Expected 4 elements but got %d", elements.length));
            }
            try {
                items.add(new Item(elements[0], elements[1], Integer
                        .valueOf(elements[2]), Float.valueOf(elements[3])));
            } catch (NumberFormatException e) {
                throw new ApplicationException(e);
            }
        }
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }

    return items;
}

Scannerクラスを使用して最初の行を無視するにはどうすればよいですか?

4

3 に答える 3

8

処理を行う前にscanner.nextLine()を1回呼び出すだけで、うまくいくはずです。

于 2012-11-04T19:28:12.990 に答える
5

ループの外側としてscanner.nextLine()を呼び出すのはどうですか。

scanner.nextLine();//this would read the first line from the text file
 while (scanner.hasNext()) {
            String row = scanner.nextLine();
于 2012-11-04T19:28:54.813 に答える
2
scanner.nextLine();
while (scanner.hasNext()) {
      String row = scanner.nextLine();
      ....
于 2012-11-04T19:29:28.873 に答える