Can anyone tell me if I am using the correct code to print the occurrences in this ArrayList?

Ok, so I'm trying to loop through an ArrayList named theDateArray, search for a specific element in that list, and output how many times that element appears. When I test it in the main class, it just outputs the number 0 no matter what date as a string I enter. Here is the part of the class that contains the methods. I don't think at the moment it is necessary to include the whole class unless it gets confused ...

  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;
     }

      

Here are the compiled tickets that I am testing in my test class ....

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

    }



}

      

Here is the result I get ....

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

      

I want 0 to be 2.

+3


source to share


1 answer


I think these lines are your mistake:

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

      

Are you looking for the index frequency of your date, so in your example, the first index 2017-06-09

might be index 0? So when you do Collections.frequency ... you are looking for the frequency 0

in your date array, to which it returns 0 (no attachments).



I would try switching it to

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

      

+4


source







All Articles