我是個編程菜鳥,在從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);}
}