0

テキスト ファイルからスポーツ データを読み取るプログラムを作成しています。各行には文字列と整数が混在しており、チームのスコアだけを読み取ろうとしています。ただし、行に int がある場合でも、プログラムはスコアを出力せずにすぐに else ステートメントに進みます。スコアのない 2 つのヘッダー行をスキップするように、2 つのinput2.nextLine()ステートメントがあります。どうすればこれを修正できますか?

コードは次のとおりです。

public static void numGamesHTWon(String fileName)throws FileNotFoundException{
    System.out.print("Number of games the home team won: ");
    File statsFile = new File(fileName);
    Scanner input2 = new Scanner(statsFile);


    input2.nextLine();
    input2.nextLine();

    while (input2.hasNextLine()) {
        String line = input2.nextLine();
        Scanner lineScan = new Scanner(line);
        if(lineScan.hasNextInt()){

            System.out.println(lineScan.nextInt());
            line = input2.nextLine();

        }else{
            line = input2.nextLine();



        }
    }
}

テキストファイルの先頭は次のとおりです。

NCAA Women's Basketball
2011 - 2012
2007-11-11 Rice 63 @Winthrop 54 O1
2007-11-11 @S Dakota St 93 UC Riverside 90 O2
2007-11-11 @Texas 92 Missouri St 55
2007-11-11 Tennessee 76 Chattanooga 56
2007-11-11 Mississippi St 76 Centenary 57
2007-11-11 ETSU 75 Delaware St 72 O1 Preseason NIT
4

1 に答える 1

0

メソッドhasNextInt()は、即時文字列が int であることを確認しようとしますか? . そのため、その条件は機能していません。

public static void numGamesHTWon(String fileName) throws FileNotFoundException {
        System.out.print("Number of games the home team won: ");
        File statsFile = new File(fileName);
        Scanner input2 = new Scanner(statsFile);


        input2.nextLine();
        input2.nextLine();

        while (input2.hasNextLine()) {
            String line = input2.nextLine();
            Scanner lineScan = new Scanner(line);

            while (lineScan.hasNext()) {
                if(lineScan.hasNextInt()) {
                    System.out.println(lineScan.nextInt()); 
                    break;
                }
                lineScan.next();
            }
            line = input2.nextLine();
        }
}

このコードを試してください。

于 2015-10-23T19:15:52.977 に答える