Java:Array的第一项无法正确显示

时间:2016-06-02 01:53:57

标签: java twitter arraylist

我需要将字词与推文进行比较,并计算它们在文字上出现的次数。 我使用了两个循环来比较ArrayList和单词和ArrayList与推文,但ArrayList的第一个单词没有正确显示,不想计数。 Output Image 它应该两次支持字数

我的代码是:

用文字阅读txt并保存在arraylist

public ArrayList <String> fread(String dir) throws FileNotFoundException, IOException {
    Scanner s = new Scanner(new File(dir));
    ArrayList<String> list = new ArrayList<String>();
    while (s.hasNext()){
        list.add(s.next().toLowerCase());
    }
    s.close();
return list;
}

获取推文并将其保存在arraylist

public ArrayList<String> showTimeLine() throws TwitterException {
    List<Status> statuses = twitter.getHomeTimeline(new Paging (1,200));
    ArrayList<String> allTweets=new ArrayList<String>();
    for (Status status : statuses) {
        allTweets.add(status.getText().replaceAll("https[^\\s]+","").toLowerCase());
    }        
    return allTweets;
}

比较两个数组:

public ArrayList<String> result(ArrayList<String>tweets, ArrayList<String> palavras){
         for (int i = 0; i <palavras.size() ; i++) {
            int count = 0;
             for (int j = 0; j <tweets.size() ; j++) {
            if (tweets.get(j).contains(palavras.get(i))){
                count++;
            }
        }
        numero.add(count);
        result.add(palavras.get(i));
                }
      return result;
}

并打印

for (int i = 0; i <result.size() ; i++) {
        System.out.printf("%40s",result.get(i)+"        "+numero.get(i)+"\n");

    }

静态ArrayList:

     static ArrayList<Integer> numero = new ArrayList<Integer>();
     static ArrayList<String> result = new ArrayList<String>();

谢谢! :)

1 个答案:

答案 0 :(得分:0)

方法

public ArrayList<String> result(ArrayList<String>tweets, ArrayList<String> palavras){
     for (int i = 0; i <palavras.size() ; i++) {
        int count = 0;
         for (int j = 0; j <tweets.size() ; j++) {
        if (tweets.get(j).contains(palavras.get(i))){
            count++;
        }
    }
    numero.add(count);
    result.add(palavras.get(i));
            }
  return result;

}

您的if语句找到单个结果然后结束。您可以像这样解决此问题

public static ArrayList<String> result(ArrayList<String>tweets, ArrayList<String> palavras){
    for (int i = 0; i <palavras.size() ; i++) {
        int count = 0;
        for (int j = 0; j <tweets.size() ; j++) {
            boolean isDone = false; //NEW
            int tweetCharIter = 1; //NEW
            while (!isDone){ //NEW
                if (tweets.get(j).substring(tweetCharIter).contains(palavras.get(i))){ //ALTERED
                    tweetCharIter += tweets.get(j).substring(tweetCharIter).indexOf(palavras.get(i)) +1; //ALTERED
                    count++;
                } else { //NEW
                    isDone = true; //NEW
                }
            }
        }
        numero.add(count);
        result.add(palavras.get(i));
    }
    return result;
}