Write a method removeShorterStrings that takes an ArrayList of Strings as a para
ID: 3650237 • Letter: W
Question
Write a method removeShorterStrings that takes an ArrayList of Strings as a parameter and that removes from each successive pair of values the shorter string in the pair. For example, suppose that an ArrayList called list contains the following values: {"four", "score", "and", "seven", "years", "ago"} In the first pair, "four" and "score", the shorter string is "four". In the second pair, "and" and "seven", the shorter string is "and". In the third pair, "years" and "ago", the shorter string is "ago". Therefore, the call: removeShorterStrings(list); should remove these shorter strings, leaving the list as follows: "score", "seven", "years". If there is a tie (both strings have the same length), your method should remove the first string in the pair. If there is an odd number of strings in the list, the final value should be kept in the list.Explanation / Answer
Please rate...
Program ShorterStrings.java
==========================================================
import java.util.ArrayList;
class ShorterStrings
{
public static void main(String args[])
{
ArrayList s1=new ArrayList();
s1.add("four");s1.add("score");s1.add("and");
s1.add("seven");s1.add("years");s1.add("ago");
s1.add("extra");
int i;
System.out.println("Before Removing shorter strings:");
System.out.print("s1=[");
for(i=0;i<s1.size();i++)
{
System.out.print(s1.get(i)+" ");
}
System.out.print("] ");
removeShorterStrings(s1);
System.out.println("After Removing shorter strings:");
System.out.print("s1=[");
for(i=0;i<s1.size();i++)
{
System.out.print(s1.get(i)+" ");
}
System.out.print("] ");
}
public static void removeShorterStrings(ArrayList s1)
{
ArrayList t1=new ArrayList();
int size=s1.size();
int i;
if(size%2!=0)size=size-1;
for(i=0;i<size;i=i+2)
{
String l1=s1.get(i).toString();
String l2=s1.get(i+1).toString();
if(l1.length()<=l2.length())t1.add(s1.get(i+1));
else t1.add(s1.get(i));
}
if(s1.size()%2!=0)t1.add(s1.get(s1.size()-1));
s1.clear();
s1.addAll(t1);
}
}
=============================================================
Sample output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.