2015年9月6日 星期日

JAVA SL-275_09/06



/*
‧匿名內部類別:簡單的說就是沒有宣告名稱的類別,直接以 {....} 來實作的類別程式碼。
*/

// 利用匿名內部類別來實作 interface
// Anomouse.java

interface Pet{
        String attr="aute";
        void skill();
        void move();
}

public class Anomouse{
        public static void main(String args[]){
                Pet p = new Pet(){              //無 ;
                        public void skill(){
                                System.out.println("拎拖鞋");
                        }
                        public void move(){
                                System.out.println("移動");
                        }
                };
                p.skill();
                p.move();
        }


其中,編譯完後,會出現 Anomouse$1.class 匿名內部類別,其內容包含:
 Pet p = new Pet(){              //無 ;
                        public void skill(){
                                System.out.println("拎拖鞋");
                        }
                        public void move(){
                                System.out.println("移動");
                        }
                };
若有 n 個內部類別則會以 $流水號 來依序往後排。


/*
靜態內部類別:是在宣告時加上 static ,使其物件實體配置在記憶體 Global 區塊中。
*/

class MyOuter{
        static class MyStatic{
                public void fooA(){
                        System.out.println("Hello" + "no static");
                }
                public static void fooB(){
                        System.out.println("Hello" + " static method");
                }
        }
}

public class StaticInnerClass{
        public static void main(String args[]){
                MyOuter.MyStatic f = new MyOuter.MyStatic();
                f.fooB();
                f.fooA();
                MyOuter.MyStatic.fooB();  //配置為 static 才可以直接執行!
        }
}

/***************************************************************************************************/


‧try-catch ‧Bug 的分類: 程式語法上的錯誤。 執行時期的錯誤 ex:陣列元素索引值超出最大範圍 or 整數除以 0 邏輯的錯誤。 try{ // do something… }catch(Exception e){ // do something…(通常在這做堆疊追蹤) } Java 中用依處理錯誤的類別:Throwable, Error, Exception Error → 指的是系統本身發出的錯誤訊息,也有可能是程式所造成。 Exception → 是一個不正常的程式在執行時期所觸發的事件。 Throwable → 為 Error, Exception 的父類別,若其無法處理,則再往上丟給 JVM 處理。
JVM → Throwable → Error   Exception
try 撰寫時可將容易發生錯誤的程式碼 package 在 try 中。 catch 產生錯誤事件時,catch 進行攔截,並執行此區塊內程式碼。 */ /* ※Exception 大多放在 Input/Ouput 位置,若一開始不知道要放什麼類型的 exception, 則可以先讓程式去 run,看它出現什麼錯誤訊息。 以下為例:

public class Test{

       public static void main(String args[]){

               int arr[] = new int[5];

               arr[10] = 7;

               System.out.println("end of main method");

       }

}

故意讓它 run 出錯誤訊息,再加到 try-catch 中:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
       at Test.main(Test.java:4))
*/

public class Test{
        public static void main(String args[]){
                try{
                int arr[] = new int[5];
                arr[10] = 7;
                }catch(ArrayIndexOutOfBoundsException e){
                        System.out.println("catch to Exception");
                        System.out.println("Exception:" + e);
                        System.out.println("e.Message:" + e.getMessage());
                }
                System.out.println("end of main method");
        }
}

// Average.java
import java.util.*;

public class Average{
        public static void main(String args[]){
                Scanner scanner = new Scanner(System.in);
                double sum = 0 ;
                int count = 0;
                int number = 0 ;
                System.out.println("Key Integer Num. (exit:0):");
                while(true){
                        try{
                                number = scanner.nextInt();
                                if(number == 0 ){
                                        break;
                                }
                                sum += number ;
                                count++;
                        }catch(InputMismatchException e){
                                System.out.println("Error:Input is Integer.");
                                System.out.println("Exception Message:" + e);
                                break;
                        }
                }
                System.out.printf("平均:%.2f%n", sum/count);
        }
}


//例外繼承架構:

try{

do something…

}catch(IOException e ){ //直系子類別

e.printStackTrace();

}catch(InterruptedException e){

e.printStackTrace();
}catch(ClassCastException e){ //直系父類別
e.printStackTrace();
}

/*******************************************************************************************/

// Java 7.0 之後 → 多重捕捉 multi-catch

try{

do something…

}catch(IOException | InterruptedException | ClassCastExeption e){

e.printStackTrace(); //堆疊追蹤

}

※左邊的例外不得是右邊的父類別!

/*******************************************************************************************/

/*

‧利用 throw 丟出例外

throw 用來呼叫或傳遞一個例外,所以可以利用它在程式中觸發一個例外

*/
  1. throw 例外物件變數 →丟出一個例外物件變數
  2. throw new Exception(錯誤訊息字串) →丟出一個匿名的例外物件
/*******************************************************************************************/
// FileUtil.java
import java.io.*;
import java.util.*;

public class FileUtil{
        public static String readFile(String name)
        throws FileNotFoundException{
                StringBuilder builder = new StringBuilder();
                try{
                        Scanner scanner = new Scanner(new FileInputStream(name));
                        String text = null;
                        while(scanner.hasNext()){
                                builder.append(scanner.nextLine());
                                builder.append('\n');
                        }
                }catch(FileNotFoundException ex){
                        ex.printStackTrace();
                        throw ex;
                }
                return builder.toString();
        }
}
// Demo.java
import java.io.*;

public class Demo{
        public static void main(String args[])
        throws Exception{               // 宣告方法中拋出例外
                System.out.println(FileUtil.readFile("C:\\java\\0906\\Main.java"));
        }
        public static void doSome(String arg)
        throws FileNotFoundException, EOFException{
                try{
                        if("one".equals(arg)){
                                throw new FileNotFoundException();
                        }else{
                                throw new EOFException();
                        }
                }catch(IOException ex){
                        ex.printStackTrace();
                        throw ex;       // 執行時拋出例外
                }
        }
}

//---------------------------------------------------------------------

// 自訂路徑(要同 Demo.java 截取檔案路徑),

隨便編寫內容。 例: C:\java\0906\Main.java

Lccnet
/*******************************************************************************************/
/* 編譯出 .jar 執行檔 */ A. 以 eclipse 軟體 a. File > New > Java Project > TEST b. “TEST/src” 右鍵 > New > Class > Main3 (勾選 public static void….) import javax.swing.*; public class Main3 { public static void main(String[] args) { String s = JOptionPane.showInputDialog("Input number"); JOptionPane.showMessageDialog(null, s); } } c. 對 “TEST” 右鍵 > Export > Java > Runnable JAR file B. 以指令 jar a. 編寫檔案 Main3.java ,內容同上。 b. 編譯出 Class檔:javac Main3.java c. jar cfe myJRE.jre Main3 Main3.class

/*******************************************************************************************/
// 堆疊處理
// Main.java

public class Main {

 public static String a(){
  String text =null;
  return text.toUpperCase();
 }
 public static void b(){
  a();
 }
 public static void c(){
  try{
   b();
  }catch(NullPointerException e){
   e.printStackTrace();
   Throwable t = e.fillInStackTrace();
   throw(NullPointerException) t;
  }
 }
 public static void main(String[] args) {
  try{
   c();
  }catch(NullPointerException ex){
   ex.printStackTrace();
  }
 }
}

/*******************************************************************************************/

/*

‧ Assert 斷言

assert boolean_expression;

assert boolean_expression:detail_expression;
boolean_expression 若為 true 則什麼事都不會發生;
若為 false 則會發生 java.lang.AssertionError;
*/
//----------------------------------------------------------------------------
// AssertDemo.java

public class AssertDemo{
        final int ACTION_STOP=0;
        final int ACTION_RIGHT=1;
        final int ACTION_LEFT=2;
        final int ACTION_UP=3;

        public static void main(String args[]){
                new AssertDemo().play(0);
                new AssertDemo().play(1);
                new AssertDemo().play(2);
                new AssertDemo().play(3);
//              new AssertDemo().play(5);
                new AssertDemo().testScore(0);
                new AssertDemo().testScore(100);
                new AssertDemo().testScore(-1);
        }

        public void testScore(int score){
                assert(score >= 0 && score <= 100):"成績錯誤";
                System.out.println("score = " + score);
                assert(score >= 0 && score <= 100):"成績錯誤";
                System.out.println("score = " + score);
        }

        public void play(int action){
                switch(action){
                case ACTION_STOP:
                        System.out.println("停止撥放");
                        break;
                case ACTION_RIGHT:
                        System.out.println("向右撥放");
                        break;
                case ACTION_LEFT:
                        System.out.println("向左撥放");
                        break;
                case ACTION_UP:
                        System.out.println("向上撥放");
                        break;
                default:
                        assert false : "非定義的常數";
                }
        }
}
/* ※注意,編譯完執行要加 -ea 參數啟用Assertion
javac AssertDemo.java
java -ea AssertDemo
*/
/*******************************************************************************************/

沒有留言:

張貼留言