In this problem you will write several static methods to wor
In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester.
public static int max(int[] array) gets the maximum value in the array
public static boolean contains(String[] array, String target)determines if the target is in the array. Returns true if it is, otherwise returns false
public static ArrayList<String> wordsStartingWith(ArrayList<String> list, char letter)gets an ArrayList of all the words in the given ArrayList that start with the given letter. The comparison is case-insensitive. \'A\' and \'a\' are counted as the same letter
Output supposed to look like this
Solution
// Util.java
import java.util.ArrayList;
public class Util
{
public static boolean contains(String[] array, String target)
{
for (int i = 0; i < array.length ;i++ )
{
if(array[i].equals(target))
return true;
}
return false;
}
public static ArrayList<String> wordsStartingWith(ArrayList<String> list, char letter)
{
letter = Character.toLowerCase(letter);
ArrayList<String> result = new ArrayList<String>();
String[] array = new String[list.size()];
array = list.toArray(array);
for(String s : array)
{
s = s.toLowerCase();
if(letter == s.charAt(0))
result.add(s);
}
return result;
}
}
// UtilTester.java
import java.util.ArrayList;
public class UtilTester
{
public static void main(String[] args)
{
String[] primitiveDataTypes = {\"int\", \"double\", \"float\", \"char\",\"boolean\", \"long\", \"short\", \"byte\"};
System.out.println(Util.contains(primitiveDataTypes,\"char\"));
System.out.println(\"Expected: true\");
System.out.println(Util.contains(primitiveDataTypes, \"String\"));
System.out.println(\"Expected: false\");
ArrayList<String> words = new ArrayList<String>();
System.out.println(Util.wordsStartingWith(words, \'b\'));
System.out.println(\"Expected: []\");
words.add(\"Big\");
words.add(\"Java\");
words.add(\"is\");
words.add(\"best\");
words.add(\"Be\");
words.add(\"the\");
words.add(\"computer\");
words.add(\"CS46A\");
System.out.println(Util.wordsStartingWith(words, \'b\'));
System.out.println(\"Expected: [Big, best, Be]\");
System.out.println(Util.wordsStartingWith(words, \'B\'));
System.out.println(\"Expected: [Big, best, Be]\");
System.out.println(Util.wordsStartingWith(words, \'s\'));
System.out.println(\"Expected: []\");
}
}
/*
output:
true
Expected: true
false
Expected: false
[]
Expected: []
[Big, best, Be]
Expected: [Big, best, Be]
[Big, best, Be]
Expected: [Big, best, Be]
[]
Expected: []
*/

