После перечитывания вашего вопроса и вашего комментария я могу предположить, что вы хотите сместить весь 2D массив строк последовательно.Конечно, я также предположил, что каждая строка в этом случае имеет одинаковый размер.
Теперь я решил написать еще один ответ, который включает весь код (также шаг за шагом),так что вы можете исследовать и изменять его по своему усмотрению.
import java.util.Arrays;
public class Answer {
//testCase - 2D matrix of Strings:
private static final String[][] testCase =
{
{"A", "B", "C", "D", "E", "F", "G"},
{"0", "1", "2", "3", "4", "5", "6"},
{"a", "b", "c", "d", "e", "f", "g"}
};
private static final String testSearch = "C";
//find the index of searchString in the array of strings
private static int findIndexOf(String[] strings, String searchString) {
for (int index = 0; index < strings.length; index++)
if (strings[index].equals(searchString))
return index; //searchString found at index
return -1; //searchString not found
}
//shifting one row by one step
private static String[] shiftToRightByOneStep(String[] strings) {
String[] result = strings;
String last = strings[strings.length - 1];
System.arraycopy(strings, 0, result, 1, strings.length - 1);
result[0] = last;
return result;
}
//shifting matrix by one step
private static String[][] shiftMatrixToRightByOneStep(String[][] matrix) {
String[][] result = matrix;
for (String[] row : matrix) {
shiftToRightByOneStep(row);
}
return result;
}
public static void main(String[] args) {
String[][] myMatrix = testCase;
String find = testSearch;
int howManySteps = myMatrix[0].length - findIndexOf(myMatrix[0], find);
System.out.println("Shifting matrix by " + howManySteps + " steps");
System.out.println("Original matrix:\n" + Arrays.deepToString(testCase) + "\n_____________________________________");
System.out.println("STEPS:");
for (int step = 0; step < howManySteps; step++)
System.out.println(Arrays.deepToString(shiftMatrixToRightByOneStep(myMatrix)) + "\n_____________________________________");
//testing is it original matrix changed
// (of course it is, b/c I used references instead of copies)
System.out.println("Original matrix:\n" + Arrays.deepToString(testCase));
}
}
Вывод:
Смещение матрицы за 5 шагов
Исходная матрица:
[[A, B, C, D, E, F, G], [0, 1, 2, 3, 4, 5, 6], [a, b, c, d, e, f, g]]
ШАГИ:
[[G, A, B, C, D, E, F], [6, 0, 1, 2, 3, 4, 5], [г, a, b, c, d, e, f]]
[[F, G, A, B, C, D, E], [5, 6, 0, 1, 2, 3, 4], [f, g, a, b, c, d, e]]
[[E, F, G, A, B, C, D], [4, 5, 6, 0, 1, 2, 3], [e, f, g, a, b, c, d]]
[[D, E, F, G, A, B, C], [3, 4, 5, 6, 0, 1, 2], [d, e, f, g, a, b, c]]
[[C, D, E, F, G, A, B], [2, 3, 4, 5, 6, 0, 1], [c, d, e, f, g, a, b]]
Исходная матрица:
[[C, D, E, F, G, A, B], [2, 3, 4, 5, 6, 0, 1], [c,д, е, ж, а, б]]