A java question. Write a class ClassManager which manages an ArrayList of String
ID: 3843606 • Letter: A
Question
A java question. Write a class ClassManager which manages an ArrayList of String names. ClassManager has an ArrayList of Strings containing the names of students in the classas an instance variable. The constructor initializes the instance variable with an empty ArrayList
Provide the following methods:
public void enroll(String name) adds a name to the list of studentsenroll
public void sort() sorts the list of names. Do not write your own sort. Use the one from the Collections class in the Java library
public double averageLength() gets the average length of the names
public String getNames() gets a String consisting of all the names separated by a space.
-------------------------------------------------------------------------------------
Use the following file:
ClassManagerTester.java
Explanation / Answer
ClassManager.java
import java.util.ArrayList;
import java.util.Collections;
public class ClassManager {
ArrayList<String> names = new ArrayList<String>();
public void enroll(String name) {
names.add(name);
}
public void sort() {
Collections.sort(names);
}
public double averageLength() {
if(names.size() == 0){
return 0.0;
}
int sum = 0;
for(String name: names){
sum = sum + name.length();
}
return sum/(double)names.size();
}
public String getNames() {
String s="";
for(String name: names){
s = s + name+", ";
}
if(s.length()>0){
s = s.substring(0, s.length()-2);
}
return s;
}
}
Output:
Armand, Nick, Zane
Expected: Armand Nick Zane
Alex, Armand, Nick, Zane
Expected: Alex Armand Nick Zane
4.5
Expected: 4.5
Expected:
0.0
Expected: 0.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.