2016年10月3日 星期一

Java-建構值

Java 中物件需要建構子 (constructor) ,如果class 沒有定義建構子,JVM 就會提供一個預設的建構子


import javax.swing.JOptionPane;

public class Demo01 {

/* 建構子
* 1.寫法跟方法差不多(無回傳值)
* 2.一樣可以有傳入值
* 3.有預設值
* 4.名稱與class一樣(包含大小寫)
* 5.建構值主要初始化class
* 6.建構值new時建立class不一定第一個執行
*/
/*
* static 代碼塊
*  最早執行 且執行一次
*/
static{
System.out.println("我是 static 代碼塊");
//JOptionPane.showMessageDialog(null, "最新消息");
}
/*
* 代碼塊
* 比建構值早執行但每次呼叫都會執行
* 執行完資源釋放
*/
{
System.out.println("我是代碼塊");
JOptionPane.showMessageDialog(null, "最新消息");
}

public Demo01(){
System.out.println("我是建構值!!");
//JOptionPane.showMessageDialog(null, "最新消息");
}
public Demo01(int a){
System.out.println("我是建構值!!");
//JOptionPane.showMessageDialog(null, "最新消息");
}
public Demo01(String a){
System.out.println("我是建構值!!");
//JOptionPane.showMessageDialog(null, "最新消息");
}

public void show(){
System.out.println("我是方法!!");
}
}

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

}



結果: