You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中打印二维数组的指定行与指定列

Java二维数组指定行/列打印实现

需求

  • 基于给定的4×4二维字符串数组,打印指定索引行:索引为2的行输出拼接结果 IJKL
  • 打印指定索引列:索引为3的列输出拼接结果 DHLP

实现代码

import java.util.Scanner;

public class Test2 {
    // 打印指定行的方法
    public static void printRow(String[][] arr, int rowIndex) {
        // 行索引合法性校验
        if (rowIndex < 0 || rowIndex >= arr.length) {
            System.out.println("行索引不合法");
            return;
        }
        for (int col = 0; col < arr[rowIndex].length; col++) {
            System.out.print(arr[rowIndex][col]);
        }
        System.out.println();
    }

    // 打印指定列的方法
    public static void printColumn(String[][] arr, int colIndex) {
        for (int row = 0; row < arr.length; row++) {
            // 列索引合法性校验,避免不规则数组越界
            if (colIndex < 0 || colIndex >= arr[row].length) {
                System.out.println("列索引不合法");
                return;
            }
            System.out.print(arr[row][colIndex]);
        }
        System.out.println();
    }

    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"}};

        // 原有全数组打印逻辑
        System.out.println("完整二维数组内容:");
        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();
        }

        // 测试需求指定的行和列
        System.out.println("\n索引为2的行输出:");
        printRow(word, 2);

        System.out.println("\n索引为3的列输出:");
        printColumn(word, 3);
    }
}

运行输出

完整二维数组内容:
A B C D 
E F G H 
I J K L 
M N O P 

索引为2的行输出:
IJKL

索引为3的列输出:
DHLP

内容的提问来源于stack exchange,提问作者Josh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 08:18:03