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

This program calculates the lengths of words in the first array and then adds them to a second array.

My Code

import java.util.ArrayList;

public class LengthsOfStrings {
    public static ArrayList<Integer> lengths(ArrayList<String> list) {
        ArrayList<Integer> lengthList = new ArrayList<Integer>();
        // write code here

        for(String word: list){
            lengthList.add(word.length());
        }
        
        return lengthList;
    }

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("Ciao");
        list.add("Moi");
        list.add("Benvenuto!");
        list.add("badger badger badger badger");
        ArrayList<Integer> lengths = lengths(list);
        
        System.out.println("The lengths of the Strings: " + lengths);
    }
}

Model code

import java.util.ArrayList;

 

public class LengthsOfStrings {

    public static ArrayList<Integer> lengths(ArrayList<String> list) {

        ArrayList<Integer> lengthList = new ArrayList<Integer>();

        // write code here

        

        for (String s : list) {

            lengthList.add(s.length());

        }

 

        return lengthList;

    }

 

    public static void main(String[] args) {

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

        list.add("Ciao");

        list.add("Moi");

        list.add("Benvenuto!");

        list.add("badger badger badger badger");

        ArrayList<Integer> lengths = lengths(list);

        

        System.out.println("The lengths of the Strings: " + lengths);

    }

}

Comments

I very nearly wrote something vastly complex to solve this before realizing it was actually very easy.

2 thoughts on “Object-Oriented Programming with Java, part I – Exercise 65”

Leave a comment