如果镜像放置在阵列的一侧,如何在打印镜像时进行输入



给定一个二维数组,如果镜像沿着阵列的一侧放置,则打印其镜像。

输入

输入的第一行将包含一个数字 T = 测试用例数。每个测试用例将包含两个正整数 n 和 m (1<=n, m<=50(,在一行上用空格分隔。接下来的 n 行将分别包含一个正好 m 个字符的字符串。下一行将包含字符"V"或"H"。如果字符为 V,则沿最右侧列垂直放置镜像。如果字符为 H,则镜像沿最底部的行水平放置。

输出

对于每个测试用例,打印 n*m 镜像 - n 行,每行包含 m 个字符的字符串。为每个测试用例输出后打印一个额外的空行。

示例输入

2
3 3
abc
def
 
ghi
V
3 4
1234
5678
9876
H

示例输出

cba
fed
ihg
9876
5678
1234

我的方法:

当我编写以下代码时,我在接受输入时遇到问题。当输入的长度等于 m 个字符时,如何停止接受输入。

下面是代码

    int arr[][]=new int[n][m];
          
     for(int j=0;j<n;j++)
          
      {   
             
        for(int k=0;k<m;k++)
             
         {
                 
            arr[j][k]=sc.nextInt(); 
                   //but if the input is in character how can i stop 
                 //I think I need to read the characters character by character and stop hen m==3(as per Sample Input)
                 //How can I do that in java
                 
         }
                 
       System.out.println();
     }      
        
    

试试这个

static void swap(String[][] array, int r1, int c1, int r2, int c2) {
    String temp = array[r1][c1];
    array[r1][c1] = array[r2][c2];
    array[r2][c2] = temp;
}
static void vertical(String[][] array) {
    int rows = array.length;
    int cols = array[0].length;
    for (int r = 0; r < rows; ++r)
        for (int c = 0; c < cols / 2; ++c)
            swap(array, r, c, r, cols - c - 1);
}
static void horizontal(String[][] array) {
    int rows = array.length;
    int cols = array[0].length;
    for (int c = 0; c < cols; ++c)
        for (int r = 0; r < rows / 2; ++r)
            swap(array, r, c, rows - r - 1, c);
}
public static void main(String[] args) {
    String s = ""
        + "2n"
        + "3 3n"
        + "abcn"
        + "defn"
        + "ghin"
        + "Vn"
        + "3 4n"
        + "1234n"
        + "5678n"
        + "9876n"
        + "Hn";
    try (Scanner scanner = new Scanner(s)) {
        int cases = scanner.nextInt();
        for (int i = 0; i < cases; ++i) {
            int rows = scanner.nextInt();
            int cols = scanner.nextInt();
            scanner.nextLine();
            String[][] array = new String[rows][cols];
            for (int r = 0; r < rows; ++r)
                array[r] = scanner.nextLine().split("");
            String operation = scanner.nextLine();
            if (operation.equals("H"))
                horizontal(array);
            else
                vertical(array);
            for (int r = 0; r < rows; ++r) {
                for (int c = 0; c < cols; ++c)
                    System.out.print(array[r][c]);
                System.out.println();
            }
        }
    }
}

最新更新