【问题标题】:printing specific rows or columns in 2 dimensional arrays在二维数组中打印特定的行或列
【发布时间】:2021-09-28 06:34:26
【问题描述】:

如何打印二维数组 ex. 中的特定行或列。我想打印第 2 列中的行 它应该是“IJKL”或打印第 3 行中的列,它应该是“DHLP”

import java.util.Scanner;

public class Test2 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        String[][] word = {{"A", "B", "C", "D", },
                            {"E", "F", "G", "H", },
                            {"I", "J", "K", "L", },
                            {"M", "N", "O", "P", }};

        for (int row = 0; row < word.length; row++) {
            for (int col = 0; col < word[row].length; col++) {
                System.out.print(word [row][col] + " ");
            }
            System.out.println();
        }
    }

}

【问题讨论】:

    标签: java multidimensional-array


    【解决方案1】:

    试试这个:

    import java.util.Scanner;
    

    公共类 MyMainClass {

    public static void main(String[] args) {
        
        Scanner input = new Scanner(System.in);
    
        String[][] word = { { "A", "B", "C", "D", }, { "E", "F", "G", "H", }, { "I", "J", "K", "L", },
                { "M", "N", "O", "P", } };
    
        for (int row = 0; row < word.length; row++) {
            for (int col = 0; col < word[row].length; col++) {
                //To Print Second Row
                if(row==2) {
                    System.out.print(word[row][col] + " ");
                }
                //To Print Third Column
                if(col==3) {
                    System.out.print(word[row][col] + " ");
                }
                
            }
            System.out.println();
        }
    
    }
    

    }

    您只需要在 if 条件中指定要显示的那些行/列...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 2015-02-05
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多