题目
输入一个3*3的矩形, 将矩形进行90度旋转后打印
样例输入:
1 2 3
4 5 6
7 8 9
样例输出:
7 4 1
8 5 2
9 6 3
分析
- 确保输入的数组是正方形数组
- 将数组旋转
- 旋转分为以下步骤
3.1 将列提取出来,
3.2 倒序成新行
3.3 组成新数组
代码
import java.util.Scanner;
public class Homwork0529 {
public static void main(String[] args) {
System.out.println("\n*******************************************************");
System.out.println("***提供一张图片, 将图片顺时针旋转90度***");
System.out.println("***输入一个3*3的矩形, 将矩形进行90度旋转后打印***");
System.out.println("*******************************************************\n");
example();
String[][] input = input();
System.out.println("\n将要转换的矩阵为:");
print(input);
System.out.println("\n*******************************************************\n");
System.out.println("转换结果为:");
method(input);
}
public static String[][] input() {
Scanner sc = new Scanner(System.in);
System.out.print("请输入第1行(用空格隔开):");
String str1 = sc.nextLine();
String[] input1 = str1.trim().split("\\s+");
int count = input1.length;
String str_temp = null;
String[] input_temp = new String[count];
String[][] input = new String[count][count];
input[0] = input1;
for(int i = 1; i < count; i++){
while (true){
System.out.print("请输入第" + (i + 1) + "行(用空格隔开):");
str_temp = sc.nextLine();
input_temp = str_temp.trim().split("\\s+");
if(input_temp.length == count){
input[i] = input_temp;
break;
}else{
System.out.print("请输入" + count + "个字符; ");
}
}
}
return input;
}
public static void print(String[][] str) {
for(int i = 0; i < str.length; i++){
for (int j = 0 ; j < str[i].length; j++){
System.out.print(str[i][j] + "\t");
}
System.out.println();
}
}
public static void method(String[][] input) {
int count = input.length;
String[][] output = new String[count][count];
String[] temp = new String[count];
for (int i = 0; i < count; i++){
for (int j = 0; j < count; j++) {
temp[j] = input[count - 1 - j][i];
}
for (int j = 0; j < temp.length; j++){
output[i][j] = temp[j];
}
}
print(output);
}
public static void example() {
String[][] s= {
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"}
};
System.out.println("范例输入:");
print(s);
System.out.println("结果如下:");
method(s);
System.out.println();
}
}
运行结果
*******************************************************
***提供一张图片, 将图片顺时针旋转90度***
***输入一个3*3的矩形, 将矩形进行90度旋转后打印***
*******************************************************
范例输入:
1 2 3
4 5 6
7 8 9
结果如下:
7 4 1
8 5 2
9 6 3
请输入第1行(用空格隔开):