JAVA中如何获取一个二维数组的行数和列数

我是个编程菜鸟,在从0开始学习编程知识。

由一道题目说开去:编写一段代码,打印出一个二维布尔数组的内容。其中*表示真,空格表示假。打印出行号和列号。

代码:

复制代码
public class Ex_11 {

    public static void printBooleans(boolean[][] a){
        
        int rowNum = a.length;
        int colNum=0;
        if(rowNum>0)
            colNum = a[0].length;
        for(int i=0;i<rowNum;i++){
            for(int j=0;j<colNum;j++){
                if(a[i][j])System.out.print("["+i+"]["+j+"]"+"*");
                else System.out.print("["+i+"]["+j+"]"+" ");
            }
            System.out.println();
        }
        
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        boolean[][] b = {{true,true,false,false},{false,false,true,true}};
        boolean[][] c={};
        printBooleans(b);
        printBooleans(c);
    }

}
复制代码

题目很简单,学到的新知识:

1.二维数组本质是一维数组,行数=数组名.length,列数=数组名[0].length;

2.列数=数组名[0].length这句之前要判断数组是否为空,若为空则数组名[0]所代表的子数字不存在,会报错。

 

public class Ex_11 {
public static void printBooleans(boolean[][] a){int rowNum = a.length;int colNum=0;if(rowNum>0)colNum = a[0].length;for(int i=0;i<rowNum;i++){for(int j=0;j<colNum;j++){if(a[i][j])System.out.print("["+i+"]["+j+"]"+"*");else System.out.print("["+i+"]["+j+"]"+" ");}System.out.println();}}
public static void main(String[] args) {// TODO Auto-generated method stubboolean[][] b = {{true,true,false,false},{false,false,true,true}};boolean[][] c={};printBooleans(b);printBooleans(c);}
}

猜你喜欢

转载自blog.csdn.net/bolang789/article/details/80141970
今日推荐