Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The following question is from this site: http://practiceit.cs.washington.edu/pr

ID: 3566573 • Letter: T

Question

The following question is from this site:

http://practiceit.cs.washington.edu/practiceit/problem.jsp?category=Building+Java+Programs%2C+3rd+edition%2FBJP3+Chapter+10&problem=bjp3-10-e2-swapPairs

I wasn't able to get it, and please don't just copy and paste answers you found on the net as the last few people who asked about this question has been getting the same replies from google results, google results that don't even compile will result in a 1 star rating thank you.

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

public void swapPairs(ArrayList<String> str){
String temp;
int i=0;
  
while(i+1<str.size()){
temp = str.get(i+1);
str.set(i+1,str.get(i));
str.set(i,temp);
i=i+2;
}
  
}