Search code examples
javatwitter

Reading text file line by line, increment different variables for different cases


File file = new File("C:\\Users\\markc\\OneDrive\\Documents\\NetBeansProjects\\TwitterTest\\src\\text\\pieChartSource.txt");
Scanner s = new Scanner(file);
int twitterWebClient = 0;
int tweetDeck = 0;
int android = 0;
int iphone = 0;
int other = 0;

while (s.hasNext()) {
    if (s.next().contains("Twitter Web Client")) {
        twitterWebClient++;
        break;
    } else if (s.next().contains("TweetDeck")) {
        tweetDeck++;
        break;
    } else if (s.next().contains("Twitter for Android")) {
        android++;
        break;
    } else if (s.next().contains("Twitter for iPhone")) {
        iphone++;
        break;
    } else {
        other++;
        break;
    }
}

s.close();

I am reading the text file named "pieChartSource", scanning each line to see if contains a certain phrase, if it does increment a variable and then break for the next line.

I then am simply printing each variable in the console.

From this instance in the image (in comments), other has 1, and all of the other values have 0.

Any ideas as to why it is not properly counting?


Solution

  • Every time you call s.next(), the scanner moves along the file. I believe you can evaluate your while condition like:

    while (s.hasNextLine()) {
            String nextLine=s.nextLine();
            if (nextLine.contains("Twitter Web Client")) {
                twitterWebClient++;
            } else if (nextLine.contains("TweetDeck")) {
                tweetDeck++;
            } else if (nextLine.contains("Twitter for Android")) {
                android++;
            } else if (nextLine.contains("Twitter for iPhone")) {
                iphone++;
            } else {
                other++;
            }
    }