Spaces:
Running
Running
| Write the method | |
| int countShorter(ArrayList<String> strings, int length) | |
| which counts the number of strings in the list string that have less than length characters. | |
| Example method call: | |
| public static void main(String[] args){ | |
| ArrayList<String> test = new ArrayList<>(); | |
| test.add("Huu"); | |
| test.add("Haa"); | |
| test.add("Huhuu"); | |
| test.add("Hohoo"); | |
| int shorterthan4= countShorter(test, 4); | |
| System.out.println(shorterthan4); | |
| } | |
| Program outputs: | |
| 2 | |
| import java.util.Random; | |
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.List; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random r = new Random(); | |
| test(new String[] {"first", "second", "third", "fourth", "five", "six", "7"}, 5); | |
| test("first second third fourth programming class method java variable".split(" "), 6); | |
| test("a ab abc abcd xyz xy x z".split(" "), 2); | |
| } | |
| public static void test(String[] l, int length) { | |
| ArrayList<String> list = new ArrayList<>(Arrays.asList(l)); | |
| System.out.println("Testing with list " + list); | |
| System.out.print("Strings, that contain under " + length + " characters: "); | |
| System.out.println(countShorter(list, length)); | |
| System.out.println(""); | |
| } | |
| //ADD | |
| public static int countShorter(ArrayList<String> strings, int length) { | |
| int count = 0; | |
| for (String str: strings) { | |
| if (str.length() < length) { | |
| count++; | |
| } | |
| } | |
| return count; | |
| } | |
| } | |
| Testing with list [first, second, third, fourth, five, six, 7] | |
| Strings, that contain under 5 characters: 3 | |
| Testing with list [first, second, third, fourth, programming, class, method, java, variable] | |
| Strings, that contain under 6 characters: 4 | |
| Testing with list [a, ab, abc, abcd, xyz, xy, x, z] | |
| Strings, that contain under 2 characters: 3 | |