问题是;用户输入 2 个输入以创建一个行和列的 2D 数组。然后 2D 数组填充随机数。之后,用户再输入 1 个输入,即旋转数组多少次。这是我的问题,我不知道如何逐层旋转数字。
旋转照片
import java.util.Random;
import java.util.Scanner;
public class RandomArray
{
public static void main(String args[]){
System.out.print("Enter number of row: ");
Scanner sc=new Scanner(System.in);
int rows=sc.nextInt();
System.out.print("Enter number of column : ");
int columns=sc.nextInt();
int twoD[][]=new int[rows][columns];
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
twoD[i][j] = (int) (Math.random()* 10) ;
}
}
for(int k = 0; k < rows; k++){
for(int l = 0; l < columns; l++){
System.out.print(twoD[k][l] + " ");
}
System.out.println();
}
}
}
//For example:
// Enter number of row: 4
// Enter number of column: 4
// It will print:
// 2 9 6 3
// 2 1 4 2
// 4 1 0 1
// 7 4 2 8
//If user enter 3 as a rotation number.It should be like this:
// 3 2 1 8
// 6 1 1 2
// 9 0 4 4
// 2 2 4 7
假设您要顺时针旋转它。您可以创建另一个 2D 数组rotated
(以临时存储旋转的值(。然后循环遍历每一行r
和列c
。
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
rotated[c][columns - 1 - r] = twoD[r][c]
}
}
twoD = rotated
您可以将其放在旋转次数的循环中。