0

Below is my code. Here, i have to switch two of the names in the 2D array but i'm not sure how to do this.

Anyone knows how to do?

    import java.util.Scanner;

    public class Homeworktest {
        public static void main(String[] args) {

            String[][] people = new String[3][3];
            people[0][0] = "April";
            people[0][1] = "Jenny";
            people[0][2] = "Charlie";
            people[1][0] = "Maya";
            people[1][1] = "Daniel";
            people[1][2] = "Felix";
            people[2][0] = "Jack";
            people[2][1] = "Charlotte";
            people[2][2] = "Nick";

            for(int i = 0; i < people.length; i++) {
                String[] subarrays = seatingChart[i];
                for(int y = 0; y < people.length; y++) {
                    System.out.print(subarrays[y] + " ");
                }

                System.out.println();
            }

            public static void switchSeats(int row1, int col1, int row2, int col2) {

            }
        }
    }
1
  • Keep the value of the first one in a temporary variable, then replace the first one with the second one, and the second one with the value of the temporary variable. Commented Oct 9, 2016 at 1:21

1 Answer 1

1

To swap values of two array locations, first, hold one value in a temporary variable, assign the second location's value to the first location and lastly assign the temporary variable's value to the second location.

public static void switchSeats(String[][] people, int row1, 
                                       int col1, int row2, int col2) {

   String tmp = people[row1][col1];
   people[row1][col1] = people[row2][col2];
   people[row2][col2] = tmp;

}

In the above code, tmp serves as the temporary variable.

Sign up to request clarification or add additional context in comments.

1 Comment

This is wrong. Your second statement should be people[row1][col1] = people[row2][col2];.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.