Write a method removeShorterStrings that takes an ArrayList

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:

My code:

public static void removeShorterStrings(ArrayList<String> shorty) {

List<String> tmp = new ArrayList<>();

if (shorty.size() < 0 || shorty.size() == 1)
return;

if (shorty.size() % 2 == 0)
for (int i = 0; i < shorty.size(); i += 2) {
if (shorty.get(i).length() < shorty.get(i + 1).length())
tmp.add(shorty.get(i + 1));
else
tmp.add(shorty.get(i));

}

else {
int i = 0;

for (i = 0; i < shorty.size() - 1; i += 2) {
if (shorty.get(i).length() < shorty.get(i + 1).length())
tmp.add(shorty.get(i + 1));
else
tmp.add(shorty.get(i));

}
tmp.add(shorty.get(shorty.size() - 1));
}

shorty.clear();
for (String s : tmp)
shorty.add(s);

}

Need to pass all 5!!

Solution

public static void removeShorterStrings(ArrayList<String> shorty) {

List<String> tmp = new ArrayList<>();

if (shorty.size() < 0 || shorty.size() == 1)

return;

if (shorty.size() % 2 == 0)

for (int i = 0; i < shorty.size(); i += 2) {

if (shorty.get(i).length() < shorty.get(i + 1).length())

tmp.add(shorty.get(i + 1));

else

tmp.add(shorty.get(i));

}

else {

int i = 0;

for (i = 0; i < shorty.size() - 1; i += 2) {

if (shorty.get(i).length() < shorty.get(i + 1).length())

tmp.add(shorty.get(i + 1));

else

tmp.add(shorty.get(i));

}

tmp.add(shorty.get(shorty.size() - 1));

}

shorty.clear();

for (String s : tmp)

shorty.add(s);

}

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
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

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site