2016年10月3日 星期一

Java-利用二維陣列列印出九宮格

這次練習利用二維陣列來列印出九宮格


public class Array2 {

        //宣告一個二維陣列並且賦予值
int[][] array = new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

       //撰寫一個方法(method) 可以讓主程式呼叫
public void show(int array[][]) {
             
             
/* (1) 普通for迴圈撰寫
                 *
                 *   //先判斷有幾個陣列
* for(int i=0 ;i<array.length ;i++){
                 *
*     //在判斷每個陣列裡面有幾個數字
*     for(int j=0 ; j<array[i].length ; j++){
                 *              //列印出結果
                 *              System.out.print(array[i][j]+ " ");
                 *      }
                 *   //每個陣列完之後換行
                 *   System.out.println();
                 * }
*/
             
                //(2) 利用foreach來撰寫
for (int[] i : array) {
for (int j : i) {
System.out.print(j + " ");
}
System.out.println();
}
}

}



結果:

沒有留言:

張貼留言