Object-Oriented Programming with Java, part I – Exercise 61

In this exercise we create a method to calculate and return the number of items in the list.

My Code

import java.util.ArrayList;

public class NumberOfItems {

    // implement here the method countItems
    public static int countItems(ArrayList<String> list) {
        int numIte = 0;
        for (String word : list) {
            numIte++;
        }
        return numIte;
    }

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("Moi");
        list.add("Ciao");
        list.add("Hello");
        System.out.println("There are this many items on the list:");
        // You can remove the comment from below when the method is done
        System.out.println(countItems(list)); 
    }

}

Model Code

import java.util.ArrayList;

 

public class NumberOfItems {

 

    // implement here the method countItems

    public static int countItems(ArrayList<String> list) {

        return list.size();

    }

 

    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<String>();

        list.add("Moi");

        list.add("Ciao");

        list.add("Hello");

        System.out.println("There are this many items on the list:");

        // You can remove the comment from below when the method is done

        //System.out.println(countItems(list)); 

    }

 

}

Comments

Never write your own code when an existing method will do.

Leave a comment