Java 逐行读取文本文件,针对不同的情况增加不同的变量

Java 逐行读取文本文件,针对不同的情况增加不同的变量,java,twitter,Java,Twitter,我正在阅读名为“pieChartSource”的文本文件,扫描每一行,看看是否包含某个短语,它是否增加了一个变量,然后换行 然后,我只是在控制台中打印每个变量 从图像中的该实例(在注释中),其他值为1,所有其他值为0 是否知道它为什么不能正确计数?每次调用s.next(),扫描仪都会沿着文件移动。我相信您可以评估您的while状况,如: File file = new File("C:\\Users\\markc\\OneDrive\\Documents\\NetBeansProjects\\T

我正在阅读名为“pieChartSource”的文本文件,扫描每一行,看看是否包含某个短语,它是否增加了一个变量,然后换行

然后,我只是在控制台中打印每个变量

从图像中的该实例(在注释中),其他值为1,所有其他值为0

是否知道它为什么不能正确计数?

每次调用s.next(),扫描仪都会沿着文件移动。我相信您可以评估您的while状况,如:

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();

示例文本文件-在每个if条件下调用
.next
。执行类似于
String s=s.nextLine()
的操作,然后检查
s
您需要向我们展示文本文件的外观
,而((String str=s.next())!=null){}
应该可以正常工作。然后您才需要检查str.contains(xxx)
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++;
        }
}