Can someone help me with this??? Write a method named swapPairs that accepts an
ID: 3582160 • Letter: C
Question
Can someone help me with this???
Write a method named swapPairs that accepts an array of strings as a parameter and switches the order of values 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 array initially stores these values:
String[] a = {"four", "score", "and","seven", "years", "ago"};
swapPairs(a);
Your method should switch the first pair ("four", "score"), the second pair ("and",
"seven") and the third pair ("years", "ago"), to yield this array:
{"score", "four", "seven", "and", "ago", "years"}
If there are an odd number of values, the final element is not moved. For example, if the
original list had been:{"to", "be", "or", "not", "to", "be", "hamlet"}
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void swapPair(String[] list,int size )
{
String a;
//if list has odd number of string , then lopp till string before last string
if( size%2 != 0 )
{
size =size -1;
}
for(int i =0; i<size; i+=2)
{
//swap strings
a = list[i];
list[i]= list[i+1];
list[i+1] = a;
}
}
public static void main (String[] args) throws java.lang.Exception
{
String[] a = {"to", "be", "or", "not", "to", "be", "hamlet"};
System.out.println("Before swap: ");
for(int i =0; i<7; i++)
System.out.println(a[i]);
swapPair(a,7);
System.out.println("After swap: ");
for(int i =0; i<7; i++)
System.out.println(a[i]);
}
}
----------------------------------------------------------------------------------------------------
output1:
Before swap:
four
score
and
seven
years
ago
After swap:
score
four
seven
and
ago
years
output2:
Before swap:
to
be
or
not
to
be
hamlet
After swap:
be
to
not
or
be
to
hamlet
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.