好的,所以我要做的是遍历名为 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/