Starting Code Given for this application Models a list of
Starting Code Given for this application:
/**
* Models a list of vocabulary words
*/
public class Vocab
{
@Override
public String toString()
{
return words.toString();
}
}
Tester File:
Solve using java for an intro to java class
Solution
Vocab.java
import java.util.ArrayList;
import java.util.Collections;
public class Vocab
{
ArrayList<String> words = new ArrayList<String>();
public Vocab(ArrayList<String> list){
words = list;
}
public String longest(){
if(words == null || words.size() == 0)
return null;
String maxString = words.get(0);
for(int i=1; i<words.size(); i++){
if(maxString.length() < words.get(i).length()){
maxString = words.get(i);
}
}
return maxString;
}
public double averageLength(){
if(words == null || words.size() == 0){
return 0;
}
double average;
int sum = 0;
for(int i=0; i<words.size(); i++){
sum = sum + words.get(i).length();
}
average = sum/(double)words.size();
return average;
}
public void remove(String target){
words.removeAll(Collections.singleton(target));
}
@Override
public String toString()
{
return words.toString();
}
}
VocabTester.java
import java.util.ArrayList;
public class VocabTester
{
public static void main(String[] args)
{
ArrayList<String> theList = new ArrayList<String>();
Vocab empty = new Vocab(theList);
System.out.println(empty.longest());
System.out.println(\"Expected: null\");
System.out.println(empty.averageLength());
System.out.println(\"Expected: 0.0\");
empty.remove(\"interface\");
System.out.println(empty);
System.out.println(\"Expected: []\");
theList.add(\"polymorphism\");
theList.add(\"interface\");
theList.add(\"encapsulation\");
theList.add(\"interface\");
theList.add(\"object-oriented\");
theList.add(\"java\");
theList.add(\"programming\");
Vocab vocab = new Vocab(theList);
System.out.println(vocab.longest());
System.out.println(\"Expected: object-oriented\");
System.out.printf(\"%.2f\ \", vocab.averageLength());
System.out.println(\"Expected: 10.43\");
vocab.remove(\"interface\");
vocab.remove(\"java\");
System.out.println(vocab);
System.out.println(\"Expected: [polymorphism, encapsulation, object-oriented, programming]\");
}
}
Output:
null
Expected: null
0.0
Expected: 0.0
[]
Expected: []
object-oriented
Expected: object-oriented
10.43
Expected: 10.43
[polymorphism, encapsulation, object-oriented, programming]
Expected: [polymorphism, encapsulation, object-oriented, programming]

