簡體   English   中英

如果將鏡像放置在陣列的一側,則在打印鏡像時如何獲取輸入

[英]How to take input while printing mirror image if mirror is placed along one of the sides of the array

給定一個二維數組,如果將鏡像放置在數組的一側,則打印其鏡像。

輸入項

輸入的第一行將包含數字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 = ""
        + "2\n"
        + "3 3\n"
        + "abc\n"
        + "def\n"
        + "ghi\n"
        + "V\n"
        + "3 4\n"
        + "1234\n"
        + "5678\n"
        + "9876\n"
        + "H\n";
    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();
            }
        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM