Spaces:
Running
Running
File size: 1,906 Bytes
99aaa37 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | 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
|