As you know the first 6 letters of the English alphabet is a, b, c, d, e, f
. I want to swap(i.e. switch) the 2nd letter which is b and the fifth letter which is e. In other words, my goal is that after the code is executed my compiler will print the following: a, e, c, d, b,f
.
When I google about swapping things in an array list I keep finding examples that contain collections.swap.. Well in class we did not learn about this. I am asking that you don't include that in your answer. The following 2 lines of codes are very simple examples of the kind of thing that is supposed to be in the code that we submit. The first example is public static void swap(int i, int j, ArrayList<String> myList).
The second example is void swap(int i, int j, ArrayList myList)
The professor didn't exactly want to us to write this code from scratch. She wanted us to fix the code she gave us on the hand out the told us what we needed to do for this assignment. This is the incorrect code:
import java.util.ArrayList;
public class abc{
public static void main(String[]args){
ArrayList<String> myList= new ArrayList();
myList.add("a");
myList.add("b");
myList.add("c");
myList.add("d");
myList.add("e");
myList.add("f");
swap(1,4,myList);
System.out.println(myList);
}
public static void swap(int i, int j, ArrayList<String> myList) {
String temp = myList.get(i);
myList.add(i, myList.get(j));
myList.add(j, temp);
}
(I tried to give that a gray background like how code is supposed to look but, it didn't work out that way.)
This code prints [a, e, b, c, b, d, e, f]
but the first paragraph that I wrote explains what I'm trying to print. I spent such a long time trying to get this to work and I can't. Please help me get Jgrasp to do what I want to it to do (refer to first paragraph.) If possible please make your code look as close to the incorrect code as possible but of course I would like it to be correct.