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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM