java - 谁能告诉我是否使用了正确的代码来打印此 ArrayList 中出现的事件?

标签 java find-occurrences

好的,所以我要做的是遍历名为 theDateArray 的 ArrayList,搜索该列表中的特定项目,然后输出该项目出现的次数。当我在主类中测试它时,无论我输入什么日期作为字符串,它都只输出数字 0。这是方法所在类的部分。我不认为截至目前,有必要包括整个类(class),除非它令人困惑......

  public ArrayList<String> getTicketDates(){

           int i;

           for (i=0; i <tickets.size(); i++){
               if(tickets .get(i).getPurchased()== false){
                 theDateArray.add(tickets.get(i).getDate());
               }
             }
             for(int f=0; f<theDateArray.size();f++){
               System.out.println(theDateArray.get(f)+ " ");
             }
             return theDateArray;
           }       



     public int getTickets(String date){
         int tix= theDateArray.indexOf(date);
         int occurrences= Collections.frequency(theDateArray, tix);
         if (tix>=0){
             System.out.println(occurrences);


         }
         return occurrences;
     }

这是我在测试课上测试的虚构门票....

 public class AmusementParkTester {

public static void main(String[] args) {


    AmusementPark park1= new AmusementPark("Walden University Park");

    park1.addTicket(777, "Child", "Noah Johnson","2017-06-09" , 27.99, false);
    park1.addTicket(777, "Child", "Zachary Gibson","2017-06-09" , 27.99, false);
    System.out.println("The dates in which tickets are available are as follows: ");
    park1.getTicketDates();

            park1.getTickets("2017-06-09");

    }



}

这是我得到的输出......

    The dates in which tickets are available are as follows: 
    2017-06-09 
    2017-06-09 
    0

我希望 0 成为 2。

最佳答案

我认为这些行是你的错误:

int tix= theDateArray.indexOf(date);
int occurrences= Collections.frequency(theDateArray, tix);

您正在寻找日期索引的频率,因此在您的示例中,2017-06-09 日期的第一个索引可能是索引 0?因此,当您执行 Collections.frequency ... 时,您正在寻找日期数组中 0 的频率,它返回 0(没有出现)。

我会尝试将其切换到

// find the number of occurrences of your passed in date within the date array
int occurrences = Collections.frequency(theDateArray, date)

关于java - 谁能告诉我是否使用了正确的代码来打印此 ArrayList 中出现的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43686255/

相关文章:

java - 音频记录和播放失败-Android AudioRecord&AudioTrack

java - JFrame 与在后台运行的图像/程序具有相同的形状

linux - 找到出现的次数并将其添加到模式旁边

mysql - 统计MySQL中属于某个类别的记录

string - DAX Power BI 字符在字符串中的出现

使用递归计算更大数组中子数组的出现次数

java - Spring集成在运行时添加路由

java - JMenu 弹出窗口有时有效

java - 替换格式不正确的 XML 正文中的字符

java - 按单词出现的降序显示