搜尋此網誌

2013年10月13日 星期日

甚麼是類別

在物件導向程式設計 , 類別是一種藍圖 , 舉之前的車子為例, 車

子為實體, 而車子的設計圖稿就是所謂的類別. 有了設計圖稿才

能到工廠生產實際的車子.接下來實際示範車子這個類別的程

式碼 :




public class Car {
 /**
  * 顏色欄位
  */
 String color;
 
 /**
  * 設定車子顏色的方法
  * @param color
  */
 public void setColor(String color){
  this.color = color;
 }
 
 /**
  * 得到車子顏色的方法
  * @return
  */
 public String getColor(){
  return this.color;
 }
 
 public static void main(String[] args){
  
  Car car = new Car();//實際製造車子的實體,也就是用new這個關鍵字來創造物件.
  
  car.setColor("blue");
  
  System.out.println("The color of car is " + car.getColor());
  
 }
 
 
}





甚麼是物件

物件是相關狀態和行為的結合. 而軟體物件常常被用來模擬真實世界. 好比: 車子, 狗 , 和其他的

真實物品, 都可用物件的概念來表示. 我們以車子來做例子 , 車子這個物件可以有顏色 , 大小,

和速度之類的狀態, 然後我們可以提供相關的行為來設定和改變這些狀態. 在軟體物件我們把

狀態稱為欄位(field) , 而行為我們稱之為方法(Method). 物件導向程式設計有一個很重要的觀念--

data encapsulation(資料封裝). 所謂的資料封裝 , 就是隱藏內部狀態 , 但是透過物件的方法, 來和

其他物件或是外部應用程式達到溝通的目的.

軟體物件來做程式設計有以下好處:



  • 模組化 : 可以針對不同的應用, 維護單一物件的原始碼 , 而不會影響到其他物件的原始碼或程式 . 一旦物件創造出來後 , 便可以在應用程式內部傳遞使用.
  • 程式碼重用: 你可以利用別人已寫好的物件提供的功能 , 而不必自己從頭寫一個新的物件.
  • 除錯容易 : 如果某個物件發生問題,或是提供的功能不完善, 你可以把這個物件抽換成別的物件, 來達到需要的功能, 而不用重新寫一份新的程式.

2013年9月9日 星期一

從無到有開發一個J2EE網頁應用程式(Web Application) -1

1. 安裝應用程式伺服器(Application Server) : Tomcat
 

  1.     到http://tomcat.apache.org/download-70.cgi
  2.     選擇  Binary Distributions底下的 Core: zip, 下載回來解壓縮.


2. 在Tomcat目錄下找到\webapps這個目錄 , 在此目錄底下建立自己的專案HelloApp



3.在HelloApp底下建立一個名為WEB-INF的目錄, 和一個HelloWorldPage.jsp 檔案


4.HelloWorldPage.jsp



5. 回到apache-tomcat-6.0.29\bin這個目錄, 執行startup.bat,啟動Tomcat 伺服器.

6. 到瀏覽器打上 http://localhost:8080/HelloApp/HelloWorldPage.jsp, 就會出現如下畫面:




2013年7月10日 星期三

動態規劃求階乘解

以下用階乘做為一個簡單的應用例子.

變數result , 用來儲存運算完的結果.

用迴圈的方式, 依次取出當前值和result相乘,

迴圈跑完後就是答案了.
   

2013年6月23日 星期日

程式註解 for 甜甜圈.

 import java.util.*;  
 public class A0918 {  
      public static void main(String[] args) {  
           Scanner scan = new Scanner(System.in);//讀取使用者的輸入  
           System.out.print("請輸入三個字串,每個字串中間以空白隔開: ");  
           String[] ary1 = scan.nextLine().split(" ");//以字串間的空白做分隔,把讀入的字串存入字串陣列.  
           System.out.print("請再輸入一次: ");  
           String[] ary2 = scan.nextLine().split(" ");  
           boolean isSame = true;//預設兩次輸入的都是一樣的字  
           for (int i = 0; i < 3 && i < ary1.length && i < ary2.length; i++) {//把兩個陣列中的,三個字拿來比對.  
                if (!ary1[i].equalsIgnoreCase(ary2[i])) {//假如不一樣.  
                     isSame = false;//設定不一樣.  
                     break;//跳離迴圈.  
                }  
           }  
           if (isSame)//假如一樣.  
                System.out.println("兩次輸入相同");  
           else//假如不一樣.  
                System.out.println("兩次輸入不相同");  
      }  
 }  

學c++ , Java 未來發展

C/ C++ ,  主要用在寫韌體或者是軟體和硬體做溝通(driver)的程式設計.

許多底層的功能都是用C/C++寫的 , Windows/Linux , 作業系統底層也是用這兩個語言去寫.

至於Java呢? 比較偏重於網路和多媒體的運用 , 因為Java有很多3rd party的套件,

你不必重新寫一個功能 , 只要在合法的範圍內, 使用這些第三方套件, 再搭配上

自己寫的函式, 就可以寫出一個應用程式.

這兩個語言各擅所長 , 只要你夠厲害 , 這兩個語言都很好.


2013年6月19日 星期三

英雄聯盟 特效介紹

特效

產生特效的來源有很多,使用技能、BUFF (增益效果)、召喚師技能、道具等都可以引發特效。特效會改變目標物的基礎狀態。為了能更加融入《英雄聯盟 LoL》的世界中,對特效的了解是不可或缺的。

護甲:表示目標抵抗傷害的能力。護甲越高,受到損傷越輕。可以用技能、道具、和 BUFF 來增加或減少目標的護甲
攻速:表示目標發動普通攻擊的速度。可以用技能和道具來增加或減少目標的攻速
傷害:表示目標對其攻擊對象造成傷害的能力。有些技能可以直接對攻擊對象造成損傷。另外也可以用技能、道具、和 BUFF 來增加或減少目標的傷害力
恐懼:恐懼效果會讓目標物在一段時間內失去控制,只會漫無目的地移動
金錢:英雄會在戰鬥中隨時間持續獲得金錢,當消滅敵人時更可瞬間得到大量金錢。可以用技能、道具、和天賦來讓英雄獲得金錢的速度加快
抓取:當發動此特效時,目標物會被強制拉近施法者身邊
治癒:讓目標回復生命。效果分為立即性 (立刻回復生命) 和持續性 (在一段時間內加快生命回復速度) 兩種。某些道具能降低目標所受的治癒效果
無敵:保護目標物免於一切傷害,但目標仍可能受到負面特效的影響
擊退:當發動此特效時,目標物會被強制推離施法者身邊
吸血:當英雄攻擊敵人時並造成傷害時,可將一定比例的傷害轉化為自己的生命值
回復:讓目標加速回復生命或魔力
復活:當英雄死亡時能立刻復活,或縮短死亡等候時間
沉默:使目標無法使用技能或召喚師技能
緩速:使目標的移動速度變慢
潛行:當發動此特效時,敵人將無法看見施法者的身影,除非敵方具有偵查隱形目標的特殊能力
暈眩:使目標在一段時間內完全無法移動或使用技能和召喚師技能,並可打斷任何施用中的技能或召喚師技能

來源:http://lol.garena.tw/learn/gameplay/ability-and-effect.php

猜數字範圍註解.

 import java.awt.event.ActionEvent;  
 import java.awt.event.ActionListener;  
 import javax.swing.JButton;  
 import javax.swing.JFrame;  
 import javax.swing.JLabel;  
 import javax.swing.JTextField;  
 class Frame extends JFrame implements ActionListener {  
      JTextField setnum = new JTextField();//範圍欄位  
      JTextField txtinput = new JTextField();//使用者輸入欄位  
      JTextField txtArea = new JTextField();//提示訊息欄位.  
      JLabel j = new JLabel("請輸入範圍0~?");  
      JLabel j2 = new JLabel("請輸入任意數:");  
      JButton OK = new JButton("go");//ok按鈕  
      int set, c, num;  
      int b = 0;  
      boolean setting = true;//已設定好範圍  
      boolean right = false;//答案錯誤  
      Frame() {  
           j.setBounds(20, 10, 100, 20);//設定標籤尺寸和範圍.  
           add(j);//把標籤加入frame  
           setnum.setBounds(110, 10, 80, 20);  
           setnum.addActionListener(this);//把範圍欄位加入行為監聽器  
           add(setnum);//把範圍欄位加入frame  
           j2.setBounds(20, 50, 100, 20);  
           add(j2);  
           txtinput.setBounds(110, 50, 80, 20);  
           txtinput.addActionListener(this);  
           add(txtinput);  
           txtinput.setEditable(false);  
           txtArea.setBounds(20, 80, 170, 20);  
           txtArea.setEditable(false);  
           add(txtArea);  
           OK.addActionListener(this);  
           OK.setBounds(120, 110, 70, 20);  
           add(OK);  
           setTitle("終極密碼");//設定frame名稱.  
           setLayout(null);  
           setBounds(200, 200, 220, 180);  
           setVisible(true);  
           setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
      }  
      public void actionPerformed(ActionEvent e) {  
           if (e.getSource() == OK || e.getSource() == txtinput//當按下ok 或者 使用者觸發了 範圍設定欄位, 或是輸入猜測數字,則執行下列程式.  
                     || e.getSource() == setnum) {  
                if (setting) {//假如已設定範圍.  
                     set = Integer.parseInt(setnum.getText());//讀入設定的數字.  
                     c = set;//把數字設給c變數,  
                     if (set <= 1) {//假如設定的數字小於1  
                          txtArea.setText("請輸入大於1的任意數字");  
                     } else {  
                          num = (int) (Math.random() * c - 1) + 1;//亂數產生數字.  
                          setting = false;//因為已經設定了正確的範圍, 所以把範圍設定旗標, 設為false,   
                          txtArea.setText("請猜0~" + set + "的任意數字");  
                          txtinput.setEditable(true);//把欄位設為不可編輯.  
                          setnum.setEditable(false);  
                     }  
                } else {  
                     int g = Integer.parseInt(txtinput.getText());//把使用者讀入的字串轉為數字存到變數g.  
                     if (g >= c || g <= b) {//假如數字小於0或是超出設定的範圍.  
                          txtArea.setText("超出範圍" + b + "~" + c + "請從新輸入");  
                     } else {  
                          if (g == num) {  
                               txtArea.setText("恭喜答對拉!");  
                               right = true;  
                               OK.setEnabled(false);  
                          } else if (g > num) {  
                               c = g;  
                               txtArea.setText("錯瞜~小一些" + b + "~" + c);  
                               txtinput.setText("");  
                          } else if (g < num) {  
                               b = g;  
                               txtArea.setText("錯瞜~大一些" + b + "~" + c);  
                               txtinput.setText("");  
                          }  
                     }  
                }  
           }  
      }  
 }  
 public class Davinci_Code {  
      public static void main(String[] args) {  
           new Frame();  
      }  
 }  

2013年6月18日 星期二

數位時鐘

 import java.awt.FlowLayout;  
 import java.awt.event.ActionEvent;  
 import java.awt.event.ActionListener;  
 import java.text.SimpleDateFormat;  
 import java.util.Date;  
 import javax.swing.JFrame;  
 import javax.swing.JLabel;  
 import javax.swing.JPanel;  
 import javax.swing.Timer;  
 public class DigitalClock extends JLabel {  
      private String pattern;  
      private Timer timer;  
      private int delay;  
      public DigitalClock(String pattern) {  
           this.pattern = pattern;  
           this.delay = 1000;  
           createTimer();  
           timer.start();  
      }  
      public DigitalClock(String pattern, int delay) {  
           this.pattern = pattern;  
           this.delay = delay;  
           createTimer();  
           timer.start();  
      }  
      public DigitalClock() {  
           pattern = "hh:mm:ss a";  
           this.delay = 1000;  
           createTimer();  
           timer.start();  
      }  
      private void createTimer() {  
           timer = new Timer(delay, new ActionListener() {  
                public void actionPerformed(ActionEvent arg0) {  
                     setText(new SimpleDateFormat(pattern).format(new Date()));  
                }  
           });  
      }  
      public static void main(String[] args) {  
           JFrame frame = new JFrame();  
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
           frame.setBounds(100, 100, 229, 102);  
           JPanel contentPane = new JPanel();  
           frame.setContentPane(contentPane);  
           contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));  
           DigitalClock digitalClock = new DigitalClock();  
           contentPane.add(digitalClock);  
           frame.setVisible(true);  
      }  
 }  
參考來源 : http://tw.knowledge.yahoo.com/question/question?qid=1013061801638 , strawman

2013年6月16日 星期日

求 JAVA 程式碼註解

 import java.util.Scanner;  
 public class GuessNumber03 {  
      public static void main(String[] args) {  
           int a, b, c, d;// 四位數字a , b , c , d  
           a = (int) (Math.random() * (9)) + 1;// 1~9 , 首位數不為零.  
           b = (int) (Math.random() * (10));// 0~9  
           c = (int) (Math.random() * (10));// 0~9  
           d = (int) (Math.random() * (10));// 0~9  
           String str = String.valueOf(a) + String.valueOf(b) + String.valueOf(c)  
                     + String.valueOf(d);// 把電腦產生的隨機數字 , 組合成字串.  
           String ans = "";// 儲存使用者猜的答案  
           Scanner sc = new Scanner(System.in);// 從命令列讀取輸入的值.  
           boolean check = false;// 預設為沒有猜到答案.  
           System.out.println("請輸入四個數字,數字對且位置正確得A,位置錯誤得B");  
           int count = 0;// 紀錄猜的次數  
           while (++count <= 10) { // 限制猜的次數到10次沒答對自動結束  
                while (!check) {// 如果沒答對 , 則繼續猜  
                     ans = sc.next();// 讀取使用者輸入的數字.  
                     String[] ansTmp = ans.split("");// 把答案abcd,分開存入暫存的字串陣列.  
                     String[] inTmp = str.split("");// 把電腦的答案,分開存入暫存的字串陣列.  
                     int A = 0;  
                     int B = 0;  
                     for (int i = 0; i < ansTmp.length; i++) {// 逐各取出使用者的答案.  
                          for (int j = 0; j < ansTmp.length; j++) {// 逐各取出使用者的答案 ,  
                                                                                 // 拿來和電腦的答案比對.  
                               if (inTmp[j].equals(ansTmp[i]) && i == j)// 假如位置一樣且數字一樣  
                                                                                      // , a++  
                                    A++;  
                               else if (inTmp[j].equals(ansTmp[i]) && i != j)// 有數字但是位置不一樣.b++  
                                    B++;  
                          }  
                     }  
                     System.out.println("判斷結果" + A + "A" + B + "B");  
                     if (A == 4)// 假如4A,  
                          check = true;// 設定猜到答案  
                     if (A == 4 & B == 0)// 假如4A且B等於零 , 則印出,恭喜你,答對ㄌ  
                          System.out.println("恭喜你,答對ㄌ");  
                     break;  
                }  
           }  
           System.out.println("遊戲結束");  
      }  
 }  

Java多重按鍵偵測.

 import java.awt.Dimension;  
 import java.awt.EventQueue;  
 import java.awt.event.KeyAdapter;  
 import java.awt.event.KeyEvent;  
 import javax.swing.JFrame;  
 import javax.swing.JLabel;  
 import javax.swing.JPanel;  
 public class MKPD extends JFrame  
 {  
   public MKPD()  
   {  
    super("MKPD");  
    setDefaultCloseOperation(EXIT_ON_CLOSE);  
    setContentPane(new KeyPanel());  
    pack();  
    setVisible(true);  
   }  
   public static void main(String[] args)  
   {  
    Runnable r = new Runnable()  
           {  
            public void run()  
            {  
              new MKPD();  
            }  
           };  
    EventQueue.invokeLater(r);  
   }  
 }  
 class KeyPanel extends JPanel  
 {  
   private enum GameState { MOVED, JUMPED, MOVED_THEN_JUMPED,  
               JUMPED_THEN_MOVED };  
   private GameState gs = null;  
   private boolean rightPressed = false;  
   private boolean upPressed = false;  
   private JLabel lblStatus = null;  
   KeyPanel()  
   {  
    KeyAdapter ka = new KeyAdapter()  
            {  
              public void keyPressed(KeyEvent ke)  
              {  
               handleKeyPress(ke);  
              }  
              public void keyReleased(KeyEvent ke)  
              {  
               handleKeyRelease(ke);  
              }  
            };  
    addKeyListener(ka);  
    lblStatus = new JLabel("", JLabel.CENTER);  
    lblStatus.setPreferredSize(new Dimension(200, 50));  
    add(lblStatus);  
    setFocusable(true);  
    requestFocus();  
   }  
   private void handleKeyPress(KeyEvent ke)  
   {  
    int keyCode = ke.getKeyCode();  
    if (keyCode == KeyEvent.VK_RIGHT)  
      rightPressed = true;  
    else  
    if (keyCode == KeyEvent.VK_UP)  
      upPressed = true;  
    updateState();  
    updateLabel();  
   }  
   private void handleKeyRelease(KeyEvent ke)  
   {  
    int keyCode = ke.getKeyCode();  
    if (keyCode == KeyEvent.VK_RIGHT)  
      rightPressed = false;  
    else  
    if (keyCode == KeyEvent.VK_UP)  
      upPressed = false;  
    updateState();  
    updateLabel();  
   }  
   private void updateLabel()  
   {  
    if (gs == null)  
    {  
      lblStatus.setText("");  
      return;  
    }  
    switch (gs)  
    {  
      case MOVED_THEN_JUMPED:  
       lblStatus.setText("Moved and then jumped");  
       break;  
      case JUMPED_THEN_MOVED:  
       lblStatus.setText("Jumped and then moved");  
       break;  
      case MOVED:  
       lblStatus.setText("Moved");  
       break;  
      case JUMPED:  
       lblStatus.setText("Jumped");  
    }  
   }  
   private void updateState()  
   {  
    if (rightPressed && upPressed)  
    {  
      if (gs == GameState.MOVED)  
       gs = GameState.MOVED_THEN_JUMPED;  
      else  
      if (gs == GameState.JUMPED)  
       gs = GameState.JUMPED_THEN_MOVED;  
    }  
    else  
    if (rightPressed)  
      gs = GameState.MOVED;  
    else  
    if (upPressed)  
      gs = GameState.JUMPED;  
    else  
      gs = null;  
   }  
 }  

2013年6月15日 星期六

猜拳 麻煩幫我每句做編譯 JAVA

 import java.util.*;  
 public class Sample {  
      public static void main(String[] args) {  
           String[] gg = { "剪刀", "石頭", "布" }; // 猜拳遊戲的三種拳.  
           Scanner scan = new Scanner(System.in);// 讀取命令列輸入的選項  
           Random rand = new Random(); // 隨機數字產生器  
           int p = 0, c = 0; // p:人贏的次數 , c:電腦贏的次數   
           while (p < 2 && c < 2) {//只要電腦或是人, 其中沒有任何一方贏兩次的話, 繼續執行猜拳的迴圈.  
                System.out.println("1.剪刀 2.石頭 3.布"); //印出遊戲的玩法.  
                int player = scan.nextInt() - 1;//使用者讀入的數字減-1  
                int comp = rand.nextInt(3);//電腦傳出0-2之中的其中一個數字.  
                System.out.println("你出" + gg[player]);//顯示人出的拳  
                System.out.println("電腦出" + gg[comp]);//顯示電腦出的拳  
                switch (player - comp) {//拿人的數字減去電腦的數字去比較,  
                case -2://人出剪刀 贏 電腦布 ,   
                     p++;  
                     break;  
                case -1://人出剪刀輸電腦石頭 , 人出石頭輸電腦布.  
                     c++;  
                     break;  
                case 1://人出石頭贏電腦剪刀, 人出布贏電腦石頭.  
                     p++;  
                     break;  
                case 2://人出布輸電腦剪刀.  
                     c++;  
                     break;  
                }  
           }  
           if (p == 2)//假如人贏兩次,印出你贏了  
                System.out.println("你贏了");  
           else //若電腦先贏兩次的話 , 因為迴圈結束,所以你輸了.  
                System.out.println("你輸了");  
      }  
 }  

2013年6月14日 星期五

猜數字遊戲

 import java.io.*;  
 public class GuessNumber {  
  private int[] answerSet = new int[10*9*8*7];  
  public GuessNumber() {  
   int index=0;  
   for (int n1=0; n1<10; n1++) {  
    for (int n2=0; n2<10; n2++) {  
     if ( n2 == n1) continue;  
     for (int n3=0; n3<10; n3++) {  
      if (n3 == n2 || n3 == n1 ) continue;  
      for (int n4=0; n4<10; n4++) {  
       if ( n4==n1 || n4==n2 || n4==n3) continue;  
       answerSet[index++] = n1*1000+n2*100+n3*10+n4;  
      }  
     }  
    }  
   }  
   guess();  
  }  
  private void input(int number) {  
   System.out.print( transform(number) + ", ?A?B = ");  
   int a=0,b=0;  
   try {  
    BufferedReader br = new BufferedReader (new InputStreamReader (System.in));  
    String str = br.readLine();  
    while ( str.length() != 4 ) {  
     System.out.println("輸入錯誤, 格式為 ?A?B ");  
     System.out.print( transform(number) + ", ?A?B = ");  
     str = br.readLine();  
    }  
    a = str.charAt(0) - '0';  
    b = str.charAt(2) - '0';   
   }  
   catch (IOException e) {  
    System.out.println("輸入時發生不可預期的錯誤...");  
    System.exit(0);  
   }   
   if (a == 4) {  
    System.out.println("The answer is " + transform(number));   
    System.exit(0);  
   }  
   reduce(number,a,b);  
  }  
  private void guess() {  
   for (int i=0; i< answerSet.length; i++) {  
    if ( answerSet[i] == -1 ) continue;  
    input ( answerSet[i]);  
   }  
   System.out.println("你騙人!! 根本沒這數字, ***!");  
  }  
  private void reduce(int number, int a, int b) {  
   for (int i=0; i< answerSet.length; i++) {  
    if ( answerSet[i] == -1) continue;  
    if (getA(number,answerSet[i]) != a || getB(number,answerSet[i]) != b )  
     answerSet[i] = -1;  
   }  
   for (int i=0; i < answerSet.length; i++) {  
    if ( answerSet[i] == -1) continue;  
    System.out.print( transform(answerSet[i]) + " ");  
   }   
   System.out.println();   
  }  
  private int getA(int n1, int n2) {  
   int a=0;  
   String str1 = transform(n1);  
   String str2 = transform(n2);  
   for (int i=0; i<4; i++) {  
    if (str1.charAt(i) == str2.charAt(i) )  
     a++;  
   }  
   return a;  
  }    private String transform (int n) {  
   if ( n < 1000 )  
    return "0" + n;  
   else  
    return ""+n;  
  }  
  private int getB(int n1, int n2) {  
   int b = 0;  
   String str1 = transform(n1);  
   String str2 = transform(n2);  
   for (int i=0; i < 4; i++) {  
    for (int j=0; j<4 ; j++) {  
     if ( i == j) continue;  
     if ( str1.charAt(i) == str2.charAt(j) )  
      b++;  
    }  
   }  
   return b;  
  }  
  public static void main (String [] args) {  
   GuessNumber app = new GuessNumber();  
  }  
 }  
參考來源

2013年6月6日 星期四

Java字串比較

第一個true會成立, 是因為 equals這個api就是用來測試兩個字串是否相等, 所使用的. 第二個true會成立, 是因為 Java內部有一個字串常數池 , test2 和 test都是指到參數池裡頭同一個"test"字串 , 所以會相等. 第三個false , 是因為test3這個變數, 指到了一個新的物件, 雖然新物件的值也是"test" , 但是和物件常數池裡的"test"物件是不相同. 所以為false.
 public class StringComparison {  
      public static void main(String[] args)  
      {  
           String test = " test ";  
           String test2 = " test ";  
           String test3 = new String("test");  
           System.out.println(test.equals(test2));  
           System.out.println(test == test2);  
           System.out.println(test == test3);  
      }  
 }  

2013年5月28日 星期二

系統櫃施工圖片


 把板材依照側版 , 隔板 , 背板的分類方式放好.


連接衣櫥門板和側版的KD連結器


櫃體完成後 , 上方可以加上修飾頂版來填補間隙.


組裝櫃體的時候, 會在背後加上橫向支撐的木板.


把電器盒拆下


當牆上有電器盒 , 師傅把櫃體組合好後, 會留下放置電器盒的空間.


用鐵夾子把要組合的兩個櫃子夾好 , 然後用螺絲固定.


安裝櫃體底下的可調高度腳粒


腳粒安裝完成後的樣子


安裝系統櫃可以留下電器插孔





2013年5月21日 星期二

尋求Java程式維護專案.

我有4~5年的Java程式開發和維護的資歷 , 舉凡Spring, Hibernate , Struts , JQuery 等framework

都使用過, 維護過的程式碼有Android application , Java Web application ,  只要是和Java相關的

各類型技術, 都很有信心快速上手, 解決問題 . 誠摯希望與團隊或是公司行號合作.

合作方式可以用svn , 或是說我到客戶端直接工作.


2013年5月12日 星期日

A free memo application (行程安排應用程式)

我利用有空的時候寫了一個記事本app, 有興趣試玩的話可以站內留言

我可以把這個應用程式寄給你, 當然能得到意見的回饋是更好的.

This is a small application I wrote in my leisure.
Its purpose is for memorizing personal schedule. 
If you are interested in this application , you can leave me a message to get its archived version.

目前功能(Features):


  • 儲存記事(Save schedule)
  • 瀏覽記事(Display schedule)


2013年5月8日 星期三

讀取Java system properties (系統屬性)

 public class SystemPropertyDemo {  
      public static void main(String[]args){  
           String fileSeparator = System.getProperty("file.separator");  
           String classPath = System.getProperty("java.class.path");  
           String javaHome = System.getProperty("java.home");  
           String javaVendor = System.getProperty("java.vendor");  
           String javaVendorUrl = System.getProperty("java.vendor.url");  
           String javaVersion = System.getProperty("java.version");  
           String lineSeparator = System.getProperty("line.separator");  
           String osArch = System.getProperty("os.arch");  
           String osName = System.getProperty("os.name");  
           String osVersion = System.getProperty("os.version");  
           String pathSeparator = System.getProperty("path.separator");  
           String userDir = System.getProperty("user.dir");  
           String userHome = System.getProperty("user.home");  
           String userName = System.getProperty("user.name");  
           System.out.println(" fileSeparator: " + fileSeparator);  
           System.out.println(" classPath : " + classPath);  
           System.out.println(" javaHome : " + javaHome);  
           System.out.println(" javaVendor : " + javaVendor);  
           System.out.println(" javaVendorUrl : " + javaVendorUrl);  
           System.out.println(" javaVendorUrl : " + javaVersion);  
           System.out.println(" lineSeparator : " + lineSeparator);  
           System.out.println(" osArch : " + osArch);  
           System.out.println(" osName : " + osName);  
           System.out.println(" osVersion : " + osVersion);  
           System.out.println(" pathSeparator : " + pathSeparator);  
           System.out.println(" pathSeparator : " +userDir);  
           System.out.println(" userHome : " + userHome);  
           System.out.println(" userName : " + userName);  
      }  
 }  

2013年5月6日 星期一

static field(靜態欄位)

static field又可稱為類別欄位 , 顧名思義所有此類別創建的物件, 會共用此欄位值 , 如下例 :
 public class StaticField {  
      public static void main(String [] args){  
           Room.customer += 1;  
           Room room = new Room();  
           System.out.println(room.customer);  
      }  
 }  
 class Room {  
      static int customer = 0;  
 }  

2013年5月5日 星期日

工廠方法創造物件(factory method creating objects)

這種寫法容易維護 , 會比單純new Student()的寫法來的好. 因為以後只要改newStudent這個method, 會同步更新到所有new Student()的地方, 而不會發生漏改的情況.
 package pattern;  
 public class FactoryMethod {  
      public static void main(String [] args){  
           Factory.newStudent().print();  
      }  
 }  
 class Factory {  
      public static Student newStudent(){  
           return new Student();  
      }  
 }  
 class Student{  
      public void print(){  
           System.out.println("blank");  
      }  
 }  

Break 和 Return的用法.

1. Break 和 Return 都可以跳離迴圈. 2. 但是Return會跳出函式而不執行接下來的程式碼.
 public class BreakAndReturnDemo {  
      public static void main(String[] args){  
           printWord();  
           printWordWithReturn();  
      }  
      public static void printWord(){  
           for(int i = 0 ; i < 10 ; i++){  
                System.out.println(i);  
                if(i == 5){  
                     break;  
                }  
           }  
           System.out.println("After break for loop");  
           System.out.println("====Seperate Line========");  
      }  
      public static void printWordWithReturn(){  
           for(int i = 0 ; i < 10 ; i++){  
                System.out.println(i);  
                if(i == 5){  
                     return;  
                }  
           }  
           System.out.println("This line won't be executed.");  
      }  
 }  

2013年5月4日 星期六

英雄聯盟快速升級的方法

目前我是拿Grena競時通的能量值去換經驗值加成(每場勝利會得到雙倍的經驗值.)道具.

因為有四場的限制 , 所以我都是趁著有首勝的機會開始玩,

這樣會得到最大的經驗值 , 缺點是如果首勝用掉後 , 再來的勝利會用掉道具的勝場數

道具的效果就沒有這麼好了.




2013年4月26日 星期五

Log4j的使用方式

以下是log4j的source code拿出來做解釋

MyLoggerFactory.java: 製作MyLogger物件實體的工廠類別.


 /*  
  * Licensed to the Apache Software Foundation (ASF) under one or more  
  * contributor license agreements. See the NOTICE file distributed with  
  * this work for additional information regarding copyright ownership.  
  * The ASF licenses this file to You under the Apache License, Version 2.0  
  * (the "License"); you may not use this file except in compliance with  
  * the License. You may obtain a copy of the License at  
  *   
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *   
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  */  
 package examples.subclass;  
 import org.apache.log4j.Logger;  
 import org.apache.log4j.spi.LoggerFactory;  
 /**  
   A factory that makes new {@link MyLogger} objects.  
   See <b><a href="doc-files/MyLoggerFactory.java">source  
   code</a></b> for more details.  
   @author Ceki G&uuml;lc&uuml; */  
 public class MyLoggerFactory implements LoggerFactory {  
  /**  
    The constructor should be public as it will be called by  
    configurators in different packages. */  
  public  
  MyLoggerFactory() {  
  }  
  public  
  Logger makeNewLoggerInstance(String name) {  
   return new MyLogger(name);  
  }  
 }  

MyLogger.java: 在這裡定義每個 log level (warn, info , debug etc)想要印出的訊息.

以下這段程式碼是靜態的獨體模式(singleton design pattern)

private static MyLoggerFactory myFactory = new MyLoggerFactory();


 /*  
  * Licensed to the Apache Software Foundation (ASF) under one or more  
  * contributor license agreements. See the NOTICE file distributed with  
  * this work for additional information regarding copyright ownership.  
  * The ASF licenses this file to You under the Apache License, Version 2.0  
  * (the "License"); you may not use this file except in compliance with  
  * the License. You may obtain a copy of the License at  
  *   
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *   
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  */  
 package examples.subclass;  
 import org.apache.log4j.*;  
 /**  
   A simple example showing logger subclassing.   
   <p>See <b><a href="doc-files/MyLogger.java">source code</a></b>  
   for more details.  
   <p>See {@link MyLoggerTest} for a usage example.  
  */  
 public class MyLogger extends Logger {  
  // It's usually a good idea to add a dot suffix to the fully  
  // qualified class name. This makes caller localization to work  
  // properly even from classes that have almost the same fully  
  // qualified class name as MyLogger, e.g. MyLoggerTest.  
  static String FQCN = MyLogger.class.getName() + ".";  
  // It's enough to instantiate a factory once and for all.  
  private static MyLoggerFactory myFactory = new MyLoggerFactory();  
  /**  
    Just calls the parent constuctor.  
   */  
  public MyLogger(String name) {  
   super(name);  
  }  
  /**  
    Overrides the standard debug method by appending " world" at the  
    end of each message. */  
  public   
  void debug(Object message) {  
   super.log(FQCN, Level.DEBUG, message + " world.", null);    
  }  
  /**  
    This method overrides {@link Logger#getLogger} by supplying  
    its own factory type as a parameter.  
  */  
  public   
  static  
  Logger getLogger(String name) {  
   return Logger.getLogger(name, myFactory);   
  }  
  public  
  void trace(Object message) {  
   //super.log(FQCN, XLevel.TRACE, message, null);   
  }  
 }  

MyLoggerTest.java:

當不傳入任何參數的時候,使用預設的log設定, 並且在console輸出 (系統標準輸出介面)

或是傳入xml, properties設定檔, 套用裡面的設定值


 /*  
  * Licensed to the Apache Software Foundation (ASF) under one or more  
  * contributor license agreements. See the NOTICE file distributed with  
  * this work for additional information regarding copyright ownership.  
  * The ASF licenses this file to You under the Apache License, Version 2.0  
  * (the "License"); you may not use this file except in compliance with  
  * the License. You may obtain a copy of the License at  
  *   
  *   http://www.apache.org/licenses/LICENSE-2.0  
  *   
  * Unless required by applicable law or agreed to in writing, software  
  * distributed under the License is distributed on an "AS IS" BASIS,  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  * See the License for the specific language governing permissions and  
  * limitations under the License.  
  */  
 package examples.subclass;  
 import org.apache.log4j.*;  
 import org.apache.log4j.xml.DOMConfigurator;  
 import org.apache.log4j.PropertyConfigurator;  
 import org.apache.log4j.helpers.LogLog;  
 /**  
   A simple example showing logger subclassing.   
   <p>The example should make it clear that subclasses follow the  
   hierarchy. You should also try running this example with a <a  
   href="doc-files/mycat.bad">bad</a> and <a  
   href="doc-files/mycat.good">good</a> configuration file samples.  
   <p>See <b><a  
   href="doc-files/MyLogger.java">source code</a></b> for more details.  
 */  
 public class MyLoggerTest {  
  /**  
    When called wihtout arguments, this program will just print   
    <pre>  
     DEBUG [main] some.cat - Hello world.  
    </pre>  
    and exit.  
    <b>However, it can be called with a configuration file in XML or  
    properties format.  
   */  
  static public void main(String[] args) {  
   if(args.length == 0) {  
    // Note that the appender is added to root but that the log  
    // request is made to an instance of MyLogger. The output still  
    // goes to System.out.  
    Logger root = Logger.getRootLogger();  
    Layout layout = new PatternLayout("%p [%t] %c (%F:%L) - %m%n");  
    root.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT));  
   }  
   else if(args.length == 1) {  
    if(args[0].endsWith("xml")) {  
      DOMConfigurator.configure(args[0]);  
    } else {  
      PropertyConfigurator.configure(args[0]);  
    }  
   } else {  
    usage("Incorrect number of parameters.");  
   }  
   try {  
    MyLogger c = (MyLogger) MyLogger.getLogger("some.cat");    
    c.debug("Hello");  
   } catch(ClassCastException e) {  
    LogLog.error("Did you forget to set the factory in the config file?", e);  
   }  
  }  
  static  
  void usage(String errMsg) {  
   System.err.println(errMsg);  
   System.err.println("\nUsage: "+MyLogger.class.getName() + "[configFile]\n"  
         + " where *configFile* is an optional configuration file, "+  
               "either in properties or XML format.");  
   System.exit(1);  
  }  
 }  

2013年4月25日 星期四

用介面寫程式

用介面寫程式的好處 , 是你可以抽換運算或資料處理方式的演算法 , 而不必大幅更動程式碼

如下例 , 只要重新new 一個AnotherCustomMathAdd物件 , 把CustomMathAdd物件換掉 , 就會

得到新的結果.


 package convention;  
 public class CodingByInterface {  
      public static void main(String[] args){  
           CustomMathAdd cma = new CustomMathAdd();  
           add(cma , 1, 2);  
      }  
      public static void add(MathAdd ma , int a , int b){  
           System.out.println(ma.basicAdd(a, b));  
      }  
 }  
 interface MathAdd{  
      public int basicAdd(int a , int b);  
      public int advanceAdd(int a , int b);  
 }  
 class CustomMathAdd implements MathAdd {  
      public int basicAdd(int a, int b) {  
           return a + b;  
      }  
      public int advanceAdd(int a, int b) {  
           return a*2 + b;  
      }  
 }  
 class AnotherCustomMathAdd implements MathAdd {  
      public int basicAdd(int a, int b) {  
           return 0;  
      }  
      public int advanceAdd(int a, int b) {  
           return 1;  
      }  
 }  

2013年4月24日 星期三

Rename a file

 import java.io.File;  
 public class FileRenameDemo {  
      public static void main(String[] args){  
           File original = new File("src/dom/employee.xml");  
           boolean result = original.renameTo(new File("src/dom/employee.xml.backup"));  
           System.out.println(result);  
      }  
 }  

2013年4月23日 星期二

Set usage

Set不包含兩個同樣的元素e1 and e2 , 當e1.equals(e2)為真的時候,並且Set最多只可有一個null元素.
範例:
 import java.util.HashSet;  
 import java.util.Set;  
 public class SetDemo {  
      public static void main(String [] args){  
           String a = "a";  
           String b = a;  
           //String b = "b";  
           Set s = new HashSet();  
           s.add(a);  
           s.add(b);  
           System.out.println(s.toString());  
      }  
 }  
若變數b 宣告為:
String b = "b";
則會印出b, a

list to array

 import java.util.LinkedList;  
 public class LinkedListToArray {  
      public static void main(String[] args){  
           LinkedList<String> ll = new LinkedList<String>();  
           ll.add("1");  
           ll.add("2");  
           ll.add("3");  
           String[] array = ll.toArray(new String[0]);  
           for(int i = 0 ; i < array.length ; i++){  
                System.out.println(array[i]);  
           }  
      }  
 }  

2013年4月21日 星期日

How to read xml files in Java(Java讀取xml文件)

SAX is the Simple API for XML, originally a Java-only API employee.xml :
 <?xml version="1.0" encoding="UTF-8"?>  
 <company>  
      <employee>  
           <firstname>Michael</firstname>  
           <lastname>Jordan</lastname>  
      </employee>  
      <employee>  
           <firstname>Larry</firstname>  
           <lastname>Bird</lastname>  
      </employee>  
      <employee>  
           <firstname>Tiger</firstname>  
           <lastname>Woods</lastname>  
      </employee>  
 </company>  

W3c DOM sample :(from Java Tips):
 package dom;  
 import java.io.File;  
 import javax.xml.parsers.DocumentBuilder;  
 import javax.xml.parsers.DocumentBuilderFactory;  
 import org.w3c.dom.Document;  
 import org.w3c.dom.Element;  
 import org.w3c.dom.Node;  
 import org.w3c.dom.NodeList;  
 public class W3cDomDemo {  
      public static void main(String argv[]) {  
           try {  
                String path = "./bin/dom/employee.xml";  
                File file = new File(path);  
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
                DocumentBuilder db = dbf.newDocumentBuilder();  
                Document doc = db.parse(file);  
                doc.getDocumentElement().normalize();  
                System.out.println("Root element "  
                          + doc.getDocumentElement().getNodeName());  
                NodeList nodeLst = doc.getElementsByTagName("employee");  
                System.out.println("Information of all employees");  
                for (int s = 0; s < nodeLst.getLength(); s++) {  
                     Node fstNode = nodeLst.item(s);  
                     if (fstNode.getNodeType() == Node.ELEMENT_NODE) {  
                          Element fstElmnt = (Element) fstNode;  
                          NodeList fstNmElmntLst = fstElmnt  
                                    .getElementsByTagName("firstname");  
                          Element fstNmElmnt = (Element) fstNmElmntLst.item(0);  
                          NodeList fstNm = fstNmElmnt.getChildNodes();  
                          System.out.println("First Name : "  
                                    + ((Node) fstNm.item(0)).getNodeValue());  
                          NodeList lstNmElmntLst = fstElmnt  
                                    .getElementsByTagName("lastname");  
                          Element lstNmElmnt = (Element) lstNmElmntLst.item(0);  
                          NodeList lstNm = lstNmElmnt.getChildNodes();  
                          System.out.println("Last Name : "  
                                    + ((Node) lstNm.item(0)).getNodeValue());  
                     }  
                }  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
      }  
 }  

using Dom4j: dom4j , you must have dom4j library to execute below sample code
 package dom;  
 import org.dom4j.Document;  
 import org.dom4j.dom.DOMDocumentFactory;  
 import org.dom4j.io.SAXReader;  
 import org.w3c.dom.Element;  
 import org.w3c.dom.Node;  
 import org.w3c.dom.NodeList;  
 public class NativeDomDemo {  
   public static void main(String[] args) {  
        String path = "./bin/dom/employee.xml";  
     new NativeDomDemo().run(path);  
   }  
   public NativeDomDemo() {  
   }  
      private void run(String xmlFile) {  
           try {  
                parseDOM(xmlFile);  
           } catch (Exception e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
   protected void parseDOM(String xmlFile) throws Exception {  
     System.out.println("Loading document: " + xmlFile);  
     SAXReader reader = new SAXReader(DOMDocumentFactory.getInstance());  
     Document document = reader.read(xmlFile);  
     System.out.println("Created <dom4j> document: " + document);  
     if (document instanceof org.w3c.dom.Document) {  
       org.w3c.dom.Document domDocument = (org.w3c.dom.Document) document;  
       System.out.println("Created W3C DOM document: " + domDocument);  
       processDOM(domDocument);  
     } else {  
          System.out.println("FAILED to make a native W3C DOM document!!");  
     }  
   }  
   protected void processDOM(org.w3c.dom.Document doc) throws Exception {  
        NodeList nodeLst = doc.getElementsByTagName("employee");  
           System.out.println("Information of all employees");  
           for (int s = 0; s < nodeLst.getLength(); s++) {  
                Node fstNode = nodeLst.item(s);  
                if (fstNode.getNodeType() == Node.ELEMENT_NODE) {  
                     Element fstElmnt = (Element) fstNode;  
                     NodeList fstNmElmntLst = fstElmnt  
                               .getElementsByTagName("firstname");  
                     Element fstNmElmnt = (Element) fstNmElmntLst.item(0);  
                     NodeList fstNm = fstNmElmnt.getChildNodes();  
                     System.out.println("First Name : "  
                               + ((Node) fstNm.item(0)).getNodeValue());  
                     NodeList lstNmElmntLst = fstElmnt  
                               .getElementsByTagName("lastname");  
                     Element lstNmElmnt = (Element) lstNmElmntLst.item(0);  
                     NodeList lstNm = lstNmElmnt.getChildNodes();  
                     System.out.println("Last Name : "  
                               + ((Node) lstNm.item(0)).getNodeValue());  
                }  
           }  
   }  
 }  

2013年4月20日 星期六

用常數字串宣告取代hard-code字串.

這種寫法比較靈活 , 當下次要更改提示訊息時, 只要更動到一個地方即可. 也不會發生漏改的情形.
 package convention;  
 public class ConstantDemo {  
      private final static String prompInfo = "123";  
      public static void main(String [] args){  
           System.out.println(ConstantDemo.prompInfo);  
      }  
 }  

2013年4月16日 星期二

如何安裝GWT .

GWT安裝指引

1.開啟Eclipse, 然後選擇 Help > Install New Software..把更新連結貼到Work with這個文字欄位.

http://dl.google.com/eclipse/plugin/3.6

2.畫面中央會出現可下載的plugin清單.  把Google App Engine Java SDK and a Google Web Toolkit SDK打勾
3. 接著就是按下一步,然後同意安裝

20130416由選擇權未平倉量來做大盤分析

悶盤又來了,五月擺明了8000過不去,,至於下檔的支撐在7500~7600附近, 要等開倉幾天才能更確定

2013年4月10日 星期三

Java位元運算

& :  位元and
^  :  位元互斥or
|   :  位元or


 public class OperatorDemo {  
      public static void main(String [] args){  
           int one = 0x01;  
           int zero = 0x00;  
           System.out.println(one & zero);  
           System.out.println(one ^ zero);  
           System.out.println(one | zero);  
      }  
 }  

股市紀錄



大盤頭部形成, 偏空.

台積電頭部出現 , 偏空


新聞: 台積電第一季營收超標 創史上次高


4/25線型 , w底成形??..讓我們繼續看下去





5/6, 大盤收8169點 : 突破下降軌道線, 然後等拉回做多???



5/9, 大盤收8285, 會拉回嗎 ? 會拉到哪 ?




5/16 , 收8319 , 小小整理一下就上去了 . 會漲到哪?

2013年3月6日 星期三

動態創造物件(Create a object dynamically)

目錄架構:

DemoObject : 單純的物件
 package dynamic;  
 public class DemoObject {  
      private int id ;  
      public int getId() {  
           return id;  
      }  
      public void setId(int id) {  
           this.id = id;  
      }  
 }  

Main.java : 程式執行的地方.
 package dynamic;  
 import java.io.IOException;  
 import java.util.Properties;  
 public class Main {  
      public static void main(String [] args) throws IOException{  
           Properties properties = new Properties();  
           properties.load(Main.class.getResourceAsStream("object_name.prop"));  
           String classFullName = (String) properties.get("objectName");  
           try {  
                Class clazz = Class.forName(classFullName);  
                DemoObject dObj = (DemoObject)clazz.newInstance();  
                dObj.setId(1);  
                System.out.println(dObj.getId());  
           } catch (ClassNotFoundException e) {  
                e.printStackTrace();  
           } catch (InstantiationException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           } catch (IllegalAccessException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  

object_name.prop : 用key - value 的方式記錄完整的類別名稱.
 objectName = dynamic.DemoObject  

2013年3月2日 星期六

網頁動態表格(dynamic table)

 <html>  
 <head>  
 <script>  
 function insert()  
 {  
      var table=document.getElementById("myTable");  
      var text = document.createTextNode('test');  
      var row = table.insertRow();  
      var column1 = row.insertCell(0);  
      var column2 = row.insertCell(1);  
      column1.appendChild(text);  
      column2.innerText = "column2";  
 }  
 function del()  
 {  
      var table=document.getElementById("myTable");  
      table.deleteRow();  
 }  
 </script>  
 </head>  
 <body>  
 <table id="myTable" border="1">  
  <tr>  
   <td>1</td>  
   <td>book</td>  
  </tr>  
 </table>  
 <br>  
 <button type="button" onclick="insert()">Insert</button>  
 <button type="button" onclick="del()">Delete</button>  
 </body>  
 </html>  

網頁動態選單製作

利用css的display屬性, 達成動態隱藏或展示選單的效果
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <style>  
 #child {  
      display: none;  
 }  
 </style>  
 <script type="text/javascript">  
      function changeChildStatus() {  
           var childUl = document.getElementById('child');  
           if(childUl.style.display == 'block'){  
                childUl.style.display = 'none'  
           }else{  
                childUl.style.display = 'block'  
           }  
      }  
 </script>  
 </head>  
 <body>  
      <ul id="parent">  
           <li>child:  
                <ul id="child">  
                     <li>apple</li>  
                     <li>kiwi</li>  
                </ul>  
           </li>  
           <li>banana</li>  
           <li>tomato</li>  
      </ul>  
      <button type="button" onclick="changeChildStatus()">hide/show child</button>  
 </body>  
 </html>  

2013年2月27日 星期三

聯發科合併晨星為何要大陸獲准呢??

(中央社記者張建中新竹25日電)市場傳出,手機晶片廠聯發科合併晨星案,可望於3月獲 中

國大陸官方核准。聯發科表示,目前合併案仍無進一步確定結果。 聯發科將於5月1日合併

晨星,合併案在韓國及中國大陸審查進展備受市場關注;今天傳出 合併案可望於3月獲中國

大陸官方核准。 在市場利多傳言激勵下,晨星股價表現強勁,盤中一度漲停,達新台幣

230.5元,大漲15 元,漲幅6.96%;聯發科股價也一度達339.5元,上漲13元,漲幅3.98%。

只是聯發科指出,目前合併案仍無進一步確定結果,若有確定結果,將會對外說明。

2013年1月29日 星期二

Linked List implementation in C

#include <stdlib.h>
#include <stdio.h>

struct Node{
    int value;
    struct Node* nextNode ;
};

typedef struct Node* NodePtr;

void insert(NodePtr  , int value);
void display(NodePtr );

int main (void){

    NodePtr start = (NodePtr)malloc (sizeof(NodePtr));
    start->value = 0;
    start->nextNode = NULL;
    insert(start , 1);
    insert(start , 2);
    insert(start , 3);
    display(start);
    return 0;
}

void insert(NodePtr node , int value){
    NodePtr temp = node;
    while(temp->nextNode != NULL){
        temp = temp->nextNode;
    }
    NodePtr new = (NodePtr)malloc (sizeof(NodePtr));
    new->value = value;
    new->nextNode = NULL;
    temp->nextNode = new;
}

void display(NodePtr node){
    NodePtr temp = node;
    while(temp != NULL){
        printf("%d\n", temp->value);
        temp= temp->nextNode;
    }
}

2013年1月28日 星期一

Sizeof a c structure. C結構的大小.

Structure 會把char不足的部分, 補足到4 bytes .
#include <stdlib.h>
#include <stdio.h>

struct people{
    char name;
    int id;
};

int main(void ){

     printf("%d\n" , sizeof(struct people));
    printf("%d\n" , sizeof(char));
    printf("%d\n" , sizeof(int));
    return 0;
}

2013年1月22日 星期二

Create spring datasource in code not in xml (用程式創建spring的data source, 而非xml的方法)

1. DatasourceCreateDemo.java
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;


public class DatasourceCreateDemo {
    
    public static void main(String[] args){
    
        new Tester().testJdbcTemplate();
        
    }
}

class DataSourceFactory {
    
     public DataSource createDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("driver.class.name");
        dataSource.setUrl("sqlurl");
        dataSource.setUsername("username");
        dataSource.setPassword("password");
        return dataSource;
     }
    
}

class Tester{
    private JdbcTemplate jdbcTemplateObject;
    
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }
    
    public void testJdbcTemplate(){
        System.out.println(jdbcTemplateObject==null);
    }
}
2. spring config
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

   <bean id = "dataSourceFactory" class = "xxx.xxx.DataSourceFactory" />    
   
   <bean id = "dataSource" factory-bean = "dataSourceFactory" factory-method = "createDataSource" />
   
   <bean id="Tester" 
      class="xxx.xxx.Tester">
      <property name="dataSource"  ref="dataSource" />    
   </bean>
   
</beans>

2013年1月18日 星期五

delete all options in the select tag with JQuery (使用jquery刪除select tag裡所有的選項)

.html(string) : 把string參數 , 設給元件作為內容.

 $('#elementID').html('');

2013年1月17日 星期四

Set tomcat default encodeing (設定tomcat預設的編碼)

1. 到conf/server.xml   

2. 找到connector port = 8080的tag, 加上URIEncoding="UTF-8"  這個屬性

3. restart tomcat

2013年1月16日 星期三

JQuery getJson 用法

getJsonLoad.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-1.8.3.min.js"></script>
<script type="text/javascript">
function getFruits() {

    $.getJSON('../jsp/load_json.jsp', function(data) {

        $.each(data, function(key, val) {
            $("#fruitsBox").append('<option id="' + key + '">' + val + '</option>');
        });

    });
}
</script>
</head>
<body>
<select id = "fruitsBox"></select>

<button onclick ="getFruits()">get fruits</button> 
</body>
</html>
load_json.jsp
<%@ page contentType="text/html" import="org.json.* , java.io.*"%>
<%

    JSONObject obj = new JSONObject();
    obj.put("1", "apple");
    obj.put("2", "orange");
    obj.put("3", "pineapple");
    
    PrintWriter pw = response.getWriter();
    pw.print(obj.toString());
    
%>

Reference:JQuery getJson

用JQuery 或是 DOM 建立element

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<script src="../jquery-1.8.3.min.js"></script>
<script type="text/javascript">

function addOption(){
    
    var myComboBox = document.getElementById("myComboBox");
    var myOption = document.createElement("option"); 
    myOption.innerHTML = " Hello ";
    myComboBox.appendChild(myOption);
    
}

function addOptionByJq(){
    var myOption = document.createElement("option"); 
    myOption.innerHTML = " Hello by JQ ";
    $("#myComboBox").append(myOption)
    
    
}

</script>



<select id="myComboBox"></select>

<br>

<button onclick="addOption()">add a new option by dom manipulation</button>

<br>

<button onclick="addOptionByJq()"> add a new option by Jquery</button>

</body>
</html>
ReferenceJQuery append

JQuery load usage (JQuery load的使用方式)

load.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-1.8.3.min.js"></script>
<script type="text/javascript">

function getServerResponse(){
    $("#respone").load("../jsp/load.jsp");
}


</script>
</head>
<body>
<span id="respone"></span>
<button onclick ="getServerResponse()">get server response</button> 
</body>
</html>
load.jsp
<%@ page contentType="text/html" import="java.io.*"%>
<%
    PrintWriter pw = response.getWriter();
    pw.print("Hello");
%>

Reference jQuery - AJAX load() Method

Div and span introduction (介紹Div 和 span )

Div : 常常被使用在把一整個group的元件(elements), 套用到同一個css .:
Span: 則是使用在內部小部分元件上, 套用個別的css, 以下的例子結合div和span使用的方式 Reference :w3schools

2013年1月14日 星期一

JQuery 的type種類介紹

  1. String :  " hello " , ' hello' , '  "hello"  ' , "  \" 跳脫字元 \" "
  2. Number : 12 , 3.14 , 0.1 + 0.5 
  3. Boolean: 在Javascript 可以直接使用true or false, 例如:

  4. if ( true ) console.log( "always!" );
    if ( false ) console.log( "never!" );

  5. Object: 在javascript每件東西都是物件, 最簡單創造物件的方法,是使用物件實字,例如:
  6. 1.var x = {};
    2.var y = { name: "Pete", age: 15 };
  7. Array , 在javascript的array 是可變動長度的list, ex: var x = [];
    var y = [ 1, 2, 3 ];
  8. Plain object , 可包含零或多個key-value pairs , ex:
  9. var o = {};
    jQuery.isPlainObject( o ); // true
  10. Function ,
  11. javascript的函式可以有名字或者是匿名 任何函式都可以assign value給變數 或傳給另一個method,
    但要注意這麼做的話, 這個函式很有可能在另一個object裡被呼叫到. ex:
    function named() {}
    var handler = function() {}
全文參考自JQuery官方文件

2013年1月12日 星期六

Using Json in Java demo

import java.util.LinkedList;

import org.json.JSONArray;

public class JavaJsonDemo {

    public static void main(String[] args) {
        LinkedList<JSONArray> list = new LinkedList<JSONArray>();

        JSONArray obj = new JSONArray();
        JSONArray obj1 = new JSONArray();
        JSONArray obj2 = new JSONArray();
        obj.put("1");
        obj.put("2");
        obj.put("3");
        obj1.put("1");
        obj1.put("2");
        obj1.put("3");
        obj2.put("1");
        obj2.put("2");
        obj2.put("3");

        list.add(obj);
        list.add(obj1);
        list.add(obj2);
        System.out.print(list.toString());

    }

}

2013年1月8日 星期二

Observer pattern demo (觀察者模式)

import java.util.LinkedList;
import java.util.List;

public class ObserverPatternDemo {
    
    public static void main(String [] args){
        
    Novelist novelist = new Novelist();
    novelist.addReader(new Reader());
    novelist.addReader(new Reader());
    novelist.addReader(new Reader());
    novelist.addReader(new Reader());
    novelist.addReader(new Reader());
    novelist.notifyReaders();
        
    }

}

class Novelist  {
    
    List<InfoReceiver> readerList = new LinkedList();
    
    public void addReader(InfoReceiver reader){
        readerList.add(reader);
    }
    
    public void notifyReaders(){
        
        for(int i = 0 ; i < readerList.size() ; i++){
            Info info = new Info(i);
            readerList.get(i).readInfo(info);
        }
    }
}

class Info{
    
    int id;
    
    Info(int id){
        this.id = id;
    }
    
    public void printInfo(){
        System.out.println("reader " + this.id + " will receiver my newest book");
    }
}

interface InfoReceiver {
    
    public void readInfo(Info info);
}

class Reader implements InfoReceiver{

    @Override
    public void readInfo(Info info) {
        info.printInfo();
    }
    
}


2013年1月7日 星期一

BST with Java implementation

The removal part is all from Algorithms and Data Structures with implementations in Java and C++ . I just add some comments.


public class BST {

    public static void main(String[] args) {
        Tree myBst = new Tree();
        Node one = new Node(1);
        Node six = new Node(6);
        Node three = new Node(3);
        Node five = new Node(5);
        Node two = new Node(2);

        myBst.insert(one);
        myBst.insert(six);
        myBst.insert(three);
        myBst.insert(five);
        myBst.insert(two);
        myBst.preOrderTraversal(myBst.root);
        System.out.println("-----------------");
        myBst.remove(3);
        myBst.preOrderTraversal(myBst.root);

    }

}

class Node {
    Node leftChild;
    Node rightChild;
    int value;

    Node(int i) {
        this.value = i;
    }

    public boolean remove(int value, Node parent) {
        if (value < this.value) {//not found, keep left search
            if (leftChild != null)
                return leftChild.remove(value, this);
            else
                return false;
        } else if (value > this.value) {//not found , keep right search.
            if (rightChild != null)
                return rightChild.remove(value, this);
            else
                return false;
        } else {//found
            if (leftChild != null && rightChild != null) {//two leafs case
                this.value = rightChild.minValue();
                rightChild.remove(this.value, this);
            } else if (parent.leftChild == this) {//left node is the only one child node
                parent.leftChild = (leftChild != null) ? leftChild : rightChild;
            } else if (parent.rightChild == this) {//right node is the only one child node
                parent.rightChild = (leftChild != null) ? leftChild    : rightChild;
            }
            return true;
        }
    }

    /*
     * The minimum value of a tree is always located in the left sub tree,
     * so recursively search from left subtree. 
     */
    public int minValue() {
        if (leftChild == null)
            return value;
        else
            return leftChild.minValue();
    }

}

class Tree {

    Node root;

    public void insert(Node node) {
        if (root == null) {
            root = node;
        } else {
            Node temp = root;
            while (temp != null) {
                if (node.value >= temp.value) {
                    if (temp.rightChild == null) {
                        temp.rightChild = node;
                        break;
                    } else {
                        temp = temp.rightChild;
                    }
                } else {
                    if (temp.leftChild == null) {
                        temp.leftChild = node;
                        break;
                    } else {
                        temp = temp.leftChild;
                    }

                }
            }

        }
    }

    public boolean remove(int value) {
        if (root == null)
            return false;
        else {
            if (root.value == value) {
                Node auxRoot = new Node(0);
                auxRoot.leftChild = root;
                boolean result = root.remove(value, auxRoot);
                root = auxRoot.leftChild;
                return result;
            } else {
                return root.remove(value, null);
            }
        }
    }

    public void preOrderTraversal(Node root) {
        System.out.println(root.value);
        if (root.leftChild != null) {
            preOrderTraversal(root.leftChild);
        }
        if (root.rightChild != null) {
            preOrderTraversal(root.rightChild);
        }
    }

}

BST with c++

2013年1月5日 星期六

Java 物件equals method 的用法

Generally speaking , you must override the equals method of your own class. Otherwise , the jvm will treat two objects with the same memory address as the same.

多型介紹 (polymorphism introduction)

package helloWorld;

public class PolymorphismDemo {
    
    public static void main(String [] args){
        
        callMan(new SuperMan());
        callMan(new SpiderMan());
        callMan(new IronMan());
        callMan((IMan)new MixedHero(){});
    }
    
    private static void callMan(Man man){
        man.weapon();
    }
    
    private static void callMan(IMan man){
        man.weapon();
    }

}

abstract class MixedHero extends Man implements IMan{
    public void weapon(){
        System.out.println("I am a mixed hero");
    }
}

abstract class Man{
    protected void weapon(){
        System.out.println("Normal man is using a hammer");
    }
}

class SuperMan extends Man{
    
    public void weapon(){
        System.out.println("Superman can use his leaser eye");
    }
}

class SpiderMan extends Man{
    
    public void weapon(){
        System.out.println("Spiderman can use many high-tech stuffs");
    }
}

interface IMan{
    void weapon();
}

class IronMan implements IMan{

    @Override
    public void weapon() {
        System.out.println("Ironman (Sorry , I really don't know how to write descriptions for this character)");
    }
}