You recall the friendly IntList class (if you can get a printout of the full cla
ID: 3772209 • Letter: Y
Question
You recall the friendly IntList class (if you can get a printout of the full class definition from lecture at the front of the room). Consider the similar class StringList: public class StringList{ String value; IntList next; StringList(String v, StringList n){ value = v; next = n; } } In the space below, write iterative AND a recursive methods addCommas in the StringList that concatenates the list of Strings into a single, comma-list, e.g: StringList s1 = new StringList("Joe", new StringList(Bob", new StringList("mary",null))); System.out.printIn(s1.addCommasIterative()); // prints "Joe, Bob, Mary" System.out.printIn(s1.addCommasRecursive()); // same as iteractiveExplanation / Answer
package assignment;
public class StringListTest {
public static void main(String[] theArgs) {
StringList s1 = new StringList("Joe",
new StringList("Bob",
new StringList("Mary",null)) );
System.out.println(s1.addCommasIterative());
System.out.println(s1.addCommasRecursive());
}
}
class StringList {
String value;
StringList next;
StringList(String v, StringList n) {
value = v;
next = n;
}
String addCommasIterative() {
String str = value;
StringList nextStr = this.next;
while( nextStr != null) {
str += ", "+nextStr.value;
nextStr = nextStr.next;
}
return str;
}
String addCommasRecursive() {
return addCommasRecursive(this);
}
private String addCommasRecursive(StringList sl) {
if(sl.next == null)
return sl.value;
else
return sl.value+", "+addCommasRecursive(sl.next);
}
}
---output--
Joe, Bob, Mary
Joe, Bob, Mary
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.