Must be completed in Java. Write a method swapPairs that switches the order of v
ID: 675364 • Letter: M
Question
Must be completed in Java.
Write a method swapPairs that switches the order of values in an ArrayList of Strings in a pairwise fashion. Your method should switch the order of the first two values, then switch the order of the next two, switch the order of the next two, and so on. For example, if the list initially stores these values: {"four", "score", "and", "seven", "years", "ago"} your method should switch the first pair, "four", "score", the second pair, "and", "seven", and the third pair, "years", "ago", to yield this list: {"score", "four", "seven", "and", "ago", "years"}
If there are an odd number of values in the list, the final element is not moved. For example, if the original list had been: {"to", "be", "or", "not", "to", "be", "hamlet"} It would again switch pairs of values, but the final value, "hamlet" would not be moved, yielding this list: {"be", "to", "not", "or", "be", "to", "hamlet"}
Explanation / Answer
import java.util.*;
public class Neon
{
public static void main(String args[])
{
ArrayList<String> list =new ArrayList<String>();
list.add("four");
list.add("score");
list.add("and");
list.add("seven");
list.add("years");
list.add("ago");
list.add("queen");
System.out.println(list);
flip(list);
System.out.println(list);
}
public static void flip(ArrayList<String> list)
{
String exe;
String exe2;
if(list.size()%2==1)
{
exe2=list.get(list.size()-1);
list.remove(list.size()-1);
}
for(int i=0;i<list.size();i+=2)
{
exe=list.get(i);
list.set(i,list.get(i+1));
list.set(i+1,exe);
}
}
if(list.size()%2==1)
{
exe2=list.get(list.size());
list.add(list.size(),exe2);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.