0

CSVファイルにハッシュタグが表示される回数をカウントしようとしています。問題は、すべての列の最後の行をスキップして、75個を数える代わりに、70個しか数えないことです。コードは次のとおりです。申し訳ありませんが、Javaは初めてで、おそらく単純なものですが、理解できません。アウト。

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

public class HashtagCounter {

public static void main(String[] args) throws Exception {

    int total = 0;
    int count = 0;

    File file = new File("hashtags.csv");
    Scanner input = new Scanner(System.in);
    Scanner scan = new Scanner(file).useDelimiter(",\\s*");

    System.out.println("Please enter a hashtag");
    String keyboard = input.nextLine();



    while(scan.hasNext()){
        //System.out.println(scan.next());
        total = total + 1;

        if(scan.next().equals(keyboard)){
            count = count + 1;
        }
    }


    System.out.println("The hashtag " + keyboard + " appears " + count + " time(s), out of a total of " + total + " entries");
}
}
4

1 に答える 1

0

You're joining last entry of row with first entry of the next row. It's because of your delimiter ",\\s*" - it matches commas, but after the last entry in csv there is no comma. Use "\n|,\\s*" to match either newline character (\n) or comma. Pattern A|B matches strings that match either of sub-patterns. It's documented in: http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

于 2013-02-01T00:06:24.340 に答える