搜尋此網誌

2012年12月30日 星期日

Command design pattern (命令設計模式)

package Patern;

public class CommandPattern {
 
 public static void main(String [] args){
  
  int a = 10;
  
  if(0 <= a && a < 3){
   System.out.println(a + "is  0 - 2");
  }else if(3 <= a && a < 7){
   System.out.println(a + "is  3 - 6");
  }else{
   System.out.println(a +" is larger than 6");
  }
  
  /**
   * Following is a example of using command pattern to extract if-else expressions
   * into the class.
   */

  
  ICompare[] compareEvents = new ICompare[]{new LessEvent(), new BetweenEvent() ,new LargeEvent()}; 
  for(int i = 0 ; i < compareEvents.length ; i++){
   compareEvents[i].print(a);
  }
 }

}

interface ICompare{
 public void print(int number);
}

class LessEvent implements ICompare{

 @Override
 public void print(int a) {
  if(0 <= a && a < 3){
   System.out.println(a + "is  0 - 2");
  }
 }
}

class BetweenEvent implements ICompare{

 @Override
 public void print(int a) {
  if(3 <= a && a < 7){
   System.out.println(a + "is  3 - 6");
  }
  
 }
}

class LargeEvent implements ICompare{

 @Override
 public void print(int number) {
  if(number  > 6){
   System.out.println(number +" is larger than 6");
  }
 }
}

2012年11月25日 星期日

Regular expression


String pattern = "^(0{0,2}[0-9]|0?[1-9][0-9]|1[0-7][0-9])$";

^ :  代表一行的開始.
$: 代表一行的結束.
(  ) : 為capture group.
X | Y   : X 或 Y
X{n,m} : X 最少為n次,但不超過m次
[a-z] : a 到 z
X?  : x一次或完全沒有.

0{0,2}[0-9]

ex: 000 , 001 , 009


0?[1-9][0-9]

ex: 010  , 099


1[0-7][0-9])

ex : 100 ~ 179.

所以上列regular expression為找 000 到 179的 pattern寫法



2012年11月24日 星期六

原來Divide-and Conquer演算法,也可用在生活中

遇到很複雜又必須要處理的問題,可以使用分割-征服演算法來解決. 把大問題拆解成一個一個小問題來解決,當每個小問題都處理完畢. 自然地也把原來的大問題也同時解好了.

印出unicode字元

有些鍵盤找不到的符號,可以用unicode的方式來表達,如下例:

public class RegularExpression {
    
    public static void main(String [] args){
        char symbol = '\u00B0';
        System.out.println(symbol);
    }

}

UTF-8 的unicode table

2012年11月22日 星期四

CheckedTextView usage

CheckedTextView can be placed in the listview as a combination of checkbox and textview. This widget is very useful when you decide to let listview have a clickable item. CheckedTextView or you can check the list10 example under the view folder of android apidemos.

Focusable屬性

預設的設定上,使用者無法移動focus(焦點,也就是有外圍邊框的狀態)到此view, 若設為true,則使用者可以 拿到這個view的focus.

2012年11月14日 星期三

android在程式中設定背景顏色(background color)

要使用setBackgroundResource(R.color.white); 不可使用setBackgroundColor

2012年11月13日 星期二

Android 得到identifie resource id

Method 1: Using Java reflection features to get the resource ID.
public static int getResourceId(String name){
        int drawableId = -1 ;
        try {
            Class<drawable> res = R.drawable.class;
            Field field = res.getField(name);
            drawableId = field.getInt(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return drawableId;
    }
Method 2: Using Android Resources API.
public int getIdentifier (String name, String defType, String defPackage)

2012年11月8日 星期四

copy file from Android assets folder (由Android的assets資料夾拷貝檔案)

private void copyFile(String source, String destination) {
        InputStream srcStream;
        FileOutputStream desStream;
        try {
            srcStream = this.getResources().getAssets().open(source);
            desStream = new FileOutputStream(new File(destination));
            byte [] data= new byte [1024];
            while (srcStream.read(data) != -1) {
                desStream.write(data);
            }
            srcStream.close();
            desStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
add below expression in the AndroidManiFest.xml for getting access permission. 把這行加到AndroidManiFest.xml才有寫入權限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

folder traversal (遞迴搜尋目錄找檔案)

package lang;

import java.io.File;

public class Hello {
    
    public static void main(String[] args){
        
        isFileExisted("." , "Test.java");
            
    
    }
    
    private static boolean isFileExisted(String targetPath , String fileName){
            
            File target = new File(targetPath);
            if(target.isDirectory()){
                File [] files = target.listFiles();
                if(files != null){
                    for(int i = 0 ; i<files.length ; i++){
                        isFileExisted(files[i].getAbsolutePath(), fileName); 
                    }    
                }
                
            }else {
                
                if(fileName.equalsIgnoreCase((target.getName()))){
                    return true;
                }
            }
            return false;
    }
    
}

2012年11月7日 星期三

open sqlite database file (打開sqlite database的檔案)

Step 1:
File dbfile = new File("/sdcard/dbname.sqlite" ); 
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);

Step 2:

Write this permission expression in the AndroidManiFest.xml if you want to write a file into

device.



<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>



constraint failed

代表primary key 已經存在於table了.

2012年11月6日 星期二

打開android DDMS

Eclipse:的使用者可以 Click Window > Open Perspective > Other... > DDMS.

這樣就可以在開發程式的同時, 監控device.

OPEN DDMS

2012年11月1日 星期四

設定TextView的 text color(字體顏色)

myFolderText.setTextColor(getResources().getColor(R.color.blue));

單純用R.color.blue是無效的

2012年10月31日 星期三

Android 事件回傳值的意義.

假如你有set onclick 和 set onTouch event listener在同一個元件, 因為on touch的執行順序高

於on click , 所以會先執行on touch , 在此時如果你return true 則代表你會停留在on touch ,

那麼on click事件將不會被執行到 , 所以一定要回傳false, 讓android 系統知道touch事件已處

理完畢, 可以接著處理接下來的event.

2012年10月11日 星期四

如何初始化實體變數(How to initialize instance variable)

方法1:用constructor (建構子)
方法2:用initialize block (初始化區塊)
方法3:用final method

public class InitializeDemo {
    
    
    public static void main(String [] args){
        Student s = new Student();
        System.out.println(s.id);
    }
    
}

class Student{
    
    int id; 
    //Method 1:
    public Student(int id){
        this.id = id;
    }
    
    //Method 2:

    {
        id =1;
    }
    
    //Method 3:
    int phone = initializePhone();
    
    protected int initializePhone(){
        return 3;
    }
    
    public Student(){
        
    }
    
    
    
}
參考自Reference

2012年7月6日 星期五

Set UI component width

private void modifyViewWidth(View src, View des){
        src.measure(0, 0);
        int width = src.getMeasuredWidth();
        des.setMinimumWidth(width);
        
    }

2012年7月1日 星期日

Wrapper Class --Decoration design pattern

當你想要使用某個class的功能, 卻想改善既有功能的不足, 可以使用decoration design pattern把原有類別包裹起來, 這樣既可擁有向下相容性,又可以增加新功能.
package designpattern;

public class WrapperClassDemo {
    
    public static void main(String [] args){
        CarV1 v1= new CarV1();
        CarV2 v2 = new CarV2(v1);
        v2.run();
        v2.run(1);
        v1.run();
    }

}

class CarV1{
    public void run(){
        System.out.println(" car v1 run");
    }
}

class CarV2{
    CarV1 c1;
    public CarV2(CarV1 c1){
        this.c1= c1;
    }
    
    public void run(int i){
        System.out.println(" car v2 run " + i);
    }
    
    public void run(){
        c1.run();
    }
}

2012年6月28日 星期四

ArrayList 用法

import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {

    public static void main(String[] args) {
        List list = CollectionsDemo.getStudentList();
        for (int i = 0; i < list.size(); i++) {
            System.out.println(((Student) list.get(i)).getID());
        }
    }

    private static List getStudentList() {
        List list = new ArrayList();
        list.add(new Student(1));
        list.add(new Student(2));
        return list;
    }

}

class Student {
    int id;

    Student(int id) {
        this.id = id;
    }

    public int getID() {
        return this.id;
    }
}

Javascript version, You can use array.pop() to remove elements.
 <html>  
 <head>  
 <script language = "javascript">  
 var array = [];  
 array.push(1);  
 array.push(1);  
 array.push(1);  
 </script>  
 </head>  
 <body>  
      <script language = "javascript">  
           alert(array.length);  
      </script>  
 </body>  
 </html>  
行程安排應用程式

2012年6月27日 星期三

Android手機設定全螢幕 . no title

<application
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        >

定義android ,hdpi landscape

在android , 1 dp = 1.5 pixels,

所以當拿到800*480 pixels的圖片,

換算成android dp為

533* 320 

因此要放在res/drawable-hdpi folder-->portrait case

res/drawable-land-hdpi-->landscape case

2012年6月25日 星期一

Android findViewById()

要create UI的Instance, 儘量用findViewById

若要創造非UI的Instance,才用new.

2012年6月15日 星期五

甚麼是介面Interface

Interface顧名思義是一個用來溝通的介面,

介面可以視為是一種Java object和外部世界的合約,和連結.

外部世界可以透過介面提供給Java class本身並沒有的功能.

而Java class也可以透過實做了介面所提供的方法, 自然的拿去給外部世界辨識和使用.




2012年6月14日 星期四

Open Source MSN software

如果不想要裝windows live,又想要使用msn的朋友,可以試看看下列的open source msn 軟體, 他是跨平台的,所以無論是linux or windows都可以使用. http://www.amsn-project.net/

2012年6月13日 星期三

Java Adapter design pattern

This pattern is very useful especially when programming language such as Java which does not

support multiple-inheritance. Following example can achieve multiple-inheritance by implementing an

adapter design pattern.


package pattern;

public interface Dog {
    public String getDogSound();
}


package pattern;

public interface Cat {
    
    public String getCatSound();

}


package pattern;

public class AnimalAdapter implements Cat,Dog {

    @Override
    public String getCatSound() {
        return "Cat sound";
    }

    @Override
    public String getDogSound() {
        return "Dog sound";
    }

}

AnimalAdapter have both cat's voice and dog's voice.

package pattern;

public class Simulator {
    
    static boolean cat = true;
    public static void main(String[]args){
        AnimalAdapter aa = new AnimalAdapter();
        if(cat){
            System.out.println(aa.getCatSound());
        }else if(!cat){
            System.out.println(aa.getDogSound());
        }
    
    }
    
}

Therefore , simulator can produce cat voice or dog voice in different situations.
Reference:Wiki Article

Android FrameLayout

Activity在切換的時候會被移到背景去 

若使用FrameLayout的話可以讓View重疊顯示,而不會移到背景去

而visibility這個屬性可以定義元件是否要被看見.

visible:看得見
invisible:看不見,但還是佔有空間.
gone:看不見,也不占空間.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button android:id="@+id/pop_btn"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:text="Click Me" 
        android:onClick="onClickBtn"
        />
    
    <Button android:id="@+id/pop_btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me" 
        android:onClick="onClickBtn"
        />
</FrameLayout>

Android popup window demo

MainActivity.java
package com.example.android.popwindow;

import com.example.android.R;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.PopupWindow;

public class MainActivity extends Activity {
    
    PopupWindow pw = null;

    boolean isClicked = false;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popup_main);
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        pw = new PopupWindow(inflater.inflate(R.layout.pop_content,
                null, false), 100, 100, true);
        pw.setFocusable(false);
        
    }
    
    public void onClickBtn(View v){
        if(isClicked == true){
            pw.dismiss();
            isClicked = false;
        }else if(isClicked == false){
            pw.showAsDropDown(this.findViewById(R.id.pop_btn));
            isClicked = true;
        }
    }

}


We can use showAtLocation  to replace the showAsDropDown. Because this method is

more flexibile than the prior one.

res/layout/pop_content.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Content"
         />

</LinearLayout>
res/layout/pop_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button android:id="@+id/pop_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me" 
        android:onClick="onClickBtn"
        />
</LinearLayout>

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="14" />

    <application android:label="@string/app_name"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme">
        
        <activity android:name="com.example.android.popwindow.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Reference: Android Developer Guide

2012年6月11日 星期一

如何獲得android md5 key

因為win7預設是使用sha1而不是md5簽章,

可以輸入下列指令來取得md5加密的簽章:

keytool -v -list -alias androiddebugkey -keystore "你的debug.keystore檔案的位置" -storepass android -keypass android



如何知道android keystore的位置

站長是在win7使用eclipse開發Android程式,

因此可以利用eclipse找到debug keystore的位置.

到preferences-> android-> build-> 就會看到預設的debug store目錄了. 


如何獲得MD5 key

2012年6月8日 星期五

Activity lifecycle, 生命週期.


onCreate() :
當activity第一次被創建出來的時候呼叫此方法.
我們可以在這一個階段作初始化的動作.
接下來進入到onStart().這個階段.

onRestart():
當activity由停止到開始之前呼叫.

onStart():
當activity開始被使用者看到會呼叫.

onResume():
當activity準備開始和使用者互動時呼叫.
在這個時間點,你的activity會在activity stack的頂端.

onPause():
當系統要開始復原前一個activity的時候呼叫.
Called when the system is about to start resuming a previous activity.

onStop():
當這個activity不再被使用者看到的時候呼叫.因為另一個activity已經被恢復了.

onDestroy():
在你的activity被摧毀之前,最後一個呼叫.





Android Button click handler implementation, 按鈕onclick監聽器實作

Here is implementation 1:

You can use this implementation style when your click event is definitely performed every time.

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent" 
              android:orientation="vertical" >
    
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a Button" 
            />
</LinearLayout>
MainActivity.java
package com.example.android.demo;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.example.android.demo.R;

public class MainActivity extends Activity {

    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Button button = (Button) findViewById(R.id.button);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 Toast.makeText(MainActivity.class,"Hello, I am a Button" , Toast.LENGTH_SHORT);
             }
         });
    }
   
}

Here is implementation 2:

You can use this implementation style when your click event is not always executed.

This style is a little bit like the later-binding.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent" 
              android:orientation="vertical" >
    
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a Button" 
            android:onClick="onClickButton"
            />
</LinearLayout>
MainActivity.java
package com.example.android.demo;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.example.android.demo.R;

public class MainActivity extends Activity {

    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    public void onClickButton(View v) {
        Toast.makeText(MainActivity.class,"Hello, I am a Button" , Toast.LENGTH_SHORT);
    }
   
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.demo"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="14" />

    <application android:label="@string/app_name">
        <activity android:name=".MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


補充:

public static interface

View.OnClickListener


這是一個靜態介面用來定義當view被按下去的時候,要做的動作.



public abstract void onClick (View v)


則是要實作的方法,參數View 為被按下的View本身.
 Reference :Android developer guide

2012年6月4日 星期一

android:gravity vs android:layout_gravity

android:gravity ~~~> 指元件自己放的位置. Specifies how to place the content of an object, both on the x- and y-axis, within the object itself. android:layout_gravity ~~~>指元件放在相對於父容器或元件的位置.
Reference

2012年6月1日 星期五

Android Handler demo

package my.handler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class HandlerDemoActivity extends Activity{
    
    int count = 0;
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        final HandlerDemoActivity.MyHandler  handler = new MyHandler();
        Thread t = new Thread(){
            public void run(){
                while(true){
                    try {
                        Thread.sleep(2000);
                        Message msg = new Message();
                        Bundle msgBundle = new Bundle();
                        msgBundle.putInt("count", count);
                        msg.setData(msgBundle);
                        handler.sendMessage(msg);
                        count++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
    
                }
                                
            }
        };
        t.start();
    }
    
    class MyHandler extends Handler{
        public void handleMessage(Message msg){
            int i = (Integer) msg.getData().get("count");
            Log.d("handler", String.valueOf(i));
        }
        
    }
    

}

Surface View example

package my.surface;

import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class SurfaceActivity extends Activity {
    SurfaceActivity.MyCallBack myCallBacks = new MyCallBack();
    SurfaceView sView = null; //Create an abstract view which can display something later.
    SurfaceHolder sHolder = null;//with holder to do actual painting
    
    //This class is created for actual behaviors when meets following status :surface create , destroy and change
    private class MyCallBack implements SurfaceHolder.Callback{

        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                int height) {
            
        }

        public void surfaceCreated(SurfaceHolder holder) {
            Canvas canvas = holder.lockCanvas();
            canvas.drawColor(Color.GREEN);
            holder.unlockCanvasAndPost(canvas);
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            
        }
        
    }
    
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        sView = new SurfaceView(this);//This activity is treated as a context for the surface view.
        sHolder = sView.getHolder();//get a holder from this view to do control.
        sHolder.addCallback(myCallBacks);
        setContentView(sView);
    }

}

2012年5月31日 星期四

Java Interface can not define a synchronized method

interface所定義的方法,必須要被class實做, 如果在interface, 便把方法定義為synchronized(同步)的話, 那麼即便類別不需要做同步化的行為,也要被強迫實做synchronized, 這樣會使程式失去彈性,所以不可定義interface的方法為synchronized.

2012年5月22日 星期二

BFS implementation using queue and adjacency list

package graph;

import java.util.LinkedList;
import java.util.Queue;



public class BFS {
    
    public static int graph [][] = {
        {1,2},//0
        {0,3,4},//1
        {0,5,6},//2
        {1,7},//3
        {1,7},//4
        {2,7},//5
        {2,7},//6
        {3,4,5,6}//7
    };
    
    static Queue outPut = new LinkedList();
    static int visited [] = {-1,-1,-1,-1,-1,-1,-1,-1};//Initialize all unvisited.
    
    public static int [] findNeighbours(int v){
        return graph[v];
    }
    
    public static boolean isVisited(int v){
            if(visited[v]==1){
                return true;
            }else{
                return false;
            }
    }
    
    public static void main(String[] args) throws InterruptedException{
        outPut.offer(0);
        while(!outPut.isEmpty()){
            int vertex = (Integer)outPut.poll();
            if(!isVisited(vertex)){
                visited[vertex]=1;
                System.out.print(vertex);
                int neighbours []= findNeighbours(vertex);
                for(int i = 0 ;i<neighbours.length;i++){
                    if(!isVisited(neighbours[i])){
                        outPut.offer(neighbours[i]);
                    }
                }
                
            }
            
        }
        
        
    }
    

}

2012年5月21日 星期一

Directed Graph Traversal using recursive DFS



import java.util.Stack;

public class RecursiveDFS {

    public static int graph[][] = {

            { 1, 2 },// 0

            { 0, 3, 4 },// 1

            { 0, 5, 6 },// 2

            { 1, 7 },// 3

            { 1, 7 },// 4

            { 2, 7 },// 5

            { 2, 7 },// 6

            { 3, 4, 5, 6 } // 7

    };

    static int visited[] = { -1, -1, -1, -1, -1, -1, -1, -1 };// Initialize all
                                                                // unvisited.

    public static int[] findNeighbours(int v) {

        return graph[v];

    }

    public static boolean isVisited(int v) {
        if (visited[v] == 1)
            return true;
        else
            return false;
    }

    public static void recursiveDFS(int vertex) {
        System.out.print(vertex);
        visited[vertex] = 1;
        int neighbours[] = findNeighbours(vertex);
        for (int i = 0; i < neighbours.length; i++) {
            if (!isVisited(neighbours[i])) {
                recursiveDFS(neighbours[i]);
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        recursiveDFS(0);
    }

}

DFS(Depth First Search) using a stack with adjacency list



import java.util.Stack;



import sun.misc.Queue;



public class DFS {

   

    public static int graph [][] = {

        {1,2},//0

        {0,3,4},//1

        {0,5,6},//2

        {1,7},//3

        {1,7},//4

        {2,7},//5

        {2,7},//6

        {3,4,5,6}//7

    };

   

    static Stack stack = new Stack();

    static Queue outPut = new Queue();

    static int visited [] = {-1,-1,-1,-1,-1,-1,-1,-1};//Initialize all unvisited.

   

    public static int [] findNeighbours(int v){

        return graph[v];

    }

   

    public static boolean isVisited(int v){

            if(visited[v]==1){

                return true;

            }else{

                return false;

            }

    }

   

    public static void main(String[] args) throws InterruptedException{

        stack.push(0);

        while(!stack.empty()){

            int vertex = (Integer)stack.pop();

            if(!isVisited(vertex)){

                visited[vertex]=1;

                outPut.enqueue(vertex);

                int neighbours []= findNeighbours(vertex);

                for(int i = 0 ;i<neighbours.length;i++){

                    if(!isVisited(neighbours[i])){

                        stack.push(neighbours[i]);

                    }

                }

               

            }

           

        }

       

        while(!outPut.isEmpty()){

            System.out.print(outPut.dequeue());

        }

       

    }

   

   



}



BFS

Android preference demo (Android 偏好設定)

Shared Preferences是用來儲存應用程式設定值的好用類別.

資料會一直存活在系統,直到應用程式被移除.

透過access preference name, 可以對資料做接收或者是寫入的動作.

範例如下.

========================
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cookbook.activity_lifecycle"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        
        <activity android:name=".PreferenceDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
       
    </application>

</manifest>
PreferenceDemo.java

import com.cookbook.activity_lifecycle.R;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class PreferenceDemo extends Activity{
    
    public static final String PREFS_NAME = "ap_settings";
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pref) ;
        final Button setbutton = (Button) findViewById(R.id.setButton);
        setbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText et = (EditText)findViewById(R.id.editText1);
                SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("edit_text", et.getText().toString());
                // Commit the edits!
                editor.commit();
                et.setText("");
            }
        });
        
        final Button getButton = (Button) findViewById(R.id.getButton);
        getButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText et = (EditText)findViewById(R.id.editText1);
                SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                et.setText(settings.getString("edit_text", null));
            }
        });
    }

}

pref.xml

<?xml version="1.0" encoding="UTF-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <EditText
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10" 
            android:text="null"/>

        <Button
            android:id="@+id/setButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Set" />

        <Button
            android:id="@+id/getButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Get" />

    </LinearLayout>

Reference:Android Data Storage

2012年5月17日 星期四

Triangle Printing(三角形列印)

Following code segments will print a triangle


public class TriangleDemo {
    /**
     * printing following triangle:
     *       *
     *      **
     *     ***
     *    ****
     *   *****     
     * 
     */
    
    public static void main(String[]args){
        int level = 5;
        for(int i = level ; i > 0 ; i--){
            for(int blank = i-1 ; blank > 0  ;blank--){
                    System.out.print(" ");
            }
            for(int star = i ;star <= level ; star++){
                System.out.print("*");    
            }
            System.out.println("\n");
        }
        
    }

}

Linear Search with a recursive approach.(遞迴線性搜尋)

public class RecursiveLinearSearch {
    
    public static void main(String[]args){
        
        int array [] = {1,2,3,4,5};
        findInt(array,0,3);
        
    }
    
    public static void findInt(int numbers [] , int idx , int target){
        if(idx < numbers.length){
            if(numbers[idx]==target){
                System.out.println("Found "+target + " in " + idx);
                return;
            }else{
                System.out.println("Not Found "+target + " in " + idx);
                findInt(numbers,idx+1,target);
            }    
        }
    }

}
相關文章:Linear Search

如何翻轉android模擬器的螢幕(How to rotate the screen of an android emulator)

press Ctrl+ F11--> if you want to rotate it back, just Ctrl+F11 again.

2012年5月16日 星期三

Android toast demonstrations

1. Toast是一種短暫提示訊息, 訊息提示完後便會自動消失,
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

public class ToastDemoActivity extends Activity {
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Context context = getApplicationContext();
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}

2.我們也可以客製化自己想要的toast message. 首先將toast_layout.xml放到res/layout目錄下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toast_layout_root"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              android:background="#DAAA"
              >
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#0F1"
              />
    
    <TextView android:id="@+id/text2"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#FF2"
              />
</LinearLayout>
然後修改上一個範例的程式碼如下所示:
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class ToastDemoActivity extends Activity {
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast_layout,
                                       (ViewGroup) findViewById(R.id.toast_layout_root));

        TextView text = (TextView) layout.findViewById(R.id.text);
        text.setText("Hello! This is a custom toast!\n");
        
        TextView text2 = (TextView) layout.findViewById(R.id.text2);
        text2.setText("Hello! This is a custom toast2!");

        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();
    }
}

其中toast.setView這一行程式會把客製化之後的view, 設回toast object. 進而達到改變顯示的文字.
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);會改變toast顯示的位置
toast.setDuration(Toast.LENGTH_LONG);會改變訊息顯示的長度
參考自Android Developers Guide

Java Stack class

在實做演算法的時候,常會用到stack(堆疊),這個資料結構.

Java便提供了此方法如下:


import java.util.Stack;


public class StackDemo {
    
    public static void main(String [] args){
        Stack stack = new Stack();
        stack.push(1);
        stack.push(2);
        while(!stack.empty()){
            System.out.println(stack.pop());
        }
    }

}

2012年5月11日 星期五

Android 應用程式基礎

Android applications 並沒有一個類似main的單一entry point .

Intent是一個非同步化的message,可以用來啟動activity, service, and broadcast receivers.

Manifest file主要是用來告訴系統, 應用程式所使用到的所有元件.

參考自http://developer.android.com/guide/topics/fundamentals.html

Java Anonymous Class

package lang;

public class AnonymousClassTest {

    public static void main(String[]args){
        System.out.println(new Test().id);
    }
}


class Test{
    int id = 1;
}

What is an android intent?.

一個應用程式有三個核心的元件---activities , services, and broadcast receivers. 以上元件是透過所謂的messages,也就是intents來啟動. Intent messaging在執行時期,可以在元件之間傳遞訊息,無論這些元件是在同一個應用程式或不同的應用程式.

舉例來說, 一個用來蒐集新郵件的應用程式,有一個activity在manifest file宣告一個會回應send的 intent filter.


當你的應用程式創建了一個所謂的send action,那麼系統就會對應到那個蒐集新郵件的應用程式, 然後當你呼叫了這個


intent並起啟動了activity之後, 便寄出郵件.intent主要是用來做鬆散耦合.

參考自  Android Develop Guide

2012年5月7日 星期一

Java synchronized demo (Producer-Consumer model), 同步化範例.

package thread;

public class SynchronizeDemo {

    public static void main(String[] args) {
        Account acnt = new Account();
        Thread prod = new Thread(new Producer(acnt));
        Thread con = new Thread(new Consumer(acnt));
        Thread mon = new Thread(new Monitor(acnt));
        prod.start();
        con.start();
        mon.start();
    }

}

class Account {

    int sum = 50;

    public synchronized void withDraw() {
        try {
            if (sum <= 0) {
                this.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (sum >= 10) {
            sum -= 10;
            System.out.println("Withdraw 10");
        } else {
            System.out.println("Withdraw " + sum);
            sum -= sum;
        }
    }

    public synchronized void Deposit() {
        sum++;
        System.out.println("Deposit 1");
        this.notify();
    }

    public synchronized void printBalance() {
        if (sum <= 0) {
            System.out.println("No money now.");
        } else {
            System.out.println("Balance :" + sum);
        }
    }

}

class Producer implements Runnable {
    Account account;

    Producer(Account act) {
        this.account = act;
    }

    public void run() {
        while (true) {
            account.Deposit();
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

class Consumer implements Runnable {
    Account account;

    Consumer(Account act) {
        this.account = act;
    }

    public void run() {
        while (true) {
            account.withDraw();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

class Monitor implements Runnable {
    Account account;

    Monitor(Account act) {
        this.account = act;
    }

    public void run() {
        while (true) {
            account.printBalance();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

Thread Sleep sample , 執行緒 sleep範例.

package thread;

public class ThreadOperation {

    public static void main(String[] args) {

        Thread t1 = new Thread(new Th1());
        Thread t2 = new Thread(new Th2());
        t1.start();
        t2.start();
    }

}

class Th1 implements Runnable {

    public void run() {
        while (true) {
            System.out.println("Th1 ...");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

class Th2 implements Runnable {

    public void run() {
        while (true) {
            System.out.println("Th2 ...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

2012年5月6日 星期日

Solvaing Maze Traversal problems with a Brute-Force algorithm

/*
 * Hello.c
 *
 *  Created on: 2012/5/5
 *      Author: Administrator
 */
#include <stdio.h>
#include <stdlib.h>
#define startRow 2
#define startCol 0
#define endRow 5
#define endCol 7

void mazeTraverse(char [][8], int , int , char);
void printMaze(char[][8]);
#include <stdlib.h>
#include <stdio.h>
int main(void){
    char maze [][8]={
            {'#','#','#','#','#','#','#','#'},
            {'#','.','.','#','#','#','#','#'},
            {'.','.','#','#','.','#','#','#'},
            {'#','.','#','#','.','#','#','#'},
            {'#','.','#','#','.','#','#','#'},
            {'#','.','.','.','.','.','.','.'},
            {'#','.','#','.','#','#','.','#'},
            {'#','#','#','#','#','#','#','#'},

    };
    mazeTraverse(maze, startRow, startCol, 's');
    printMaze(maze);
    return 0;
}
void mazeTraverse(char maze[][8], int r, int c, char d) {
    maze[r][c] = 'X';
    if(r == endRow && c == endCol){
            return;
    }else{
            if ('n' == d) {
                if (maze[r][c + 1] != '#') {
                    mazeTraverse(maze, r, c+1, 'w');
                } else if (maze[r - 1][c] != '#') {
                    mazeTraverse(maze, r-1, c, 'n');
                } else if (maze[r][c + 1] != '#') {
                    mazeTraverse(maze, r, c+1, 'e');
                } else {
                    mazeTraverse(maze, r+1, c, 's');
                }
            }

            if ('e' == d) {
                if (maze[r - 1][c] != '#') {
                    mazeTraverse(maze, r-1, c, 'n');
                } else if (maze[r][c + 1] != '#') {
                    mazeTraverse(maze, r, c+1, 'e');
                } else if (maze[r + 1][c] != '#') {
                    mazeTraverse(maze, r+1, c, 's');
                } else {
                    mazeTraverse(maze, r, c-1, 'w');
                }
            }

            if ('s' == d) {
                if (maze[r][c + 1] != '#') {
                    mazeTraverse(maze, r, c+1, 'e');
                } else if (maze[r + 1][c] != '#') {
                    mazeTraverse(maze, r+1, c, 's');
                } else if (maze[r][c - 1] != '#') {
                    mazeTraverse(maze, r, c-1, 'w');
                } else {
                    mazeTraverse(maze, r-1, c, 'n');
                }
            }

            if ('w' == d) {
                if (maze[r + 1][c] != '#') {
                    mazeTraverse(maze, r+1, c, 's');
                } else if (maze[r][c - 1] != '#') {
                    mazeTraverse(maze, r, c-1, 'w');
                } else if (maze[r - 1][c] != '#') {
                    mazeTraverse(maze, r-1, c, 'n');
                } else {
                    mazeTraverse(maze, r, c+1, 'e');
                }
            }
    }

}

void printMaze(char maze[][8]) {
    int i, j;
    for (i = 0; i < 8; i++) {
        for (j = 0; j < 8; j++) {
            printf("%c", maze[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}

2012年5月4日 星期五

取消(Disable)Eclipse的參數檢查(Syntax Check)

 Windows->Preferences->General->Editors->Text Editors->Annotations->C/C++ Occurrences


左邊會列出要使用的參數檢查類型, 右邊是要不要啟用, 


把右邊的勾勾拿掉就不會做那個類型的參數檢查了.

Eclipse移除不需要的Plugin

到Eclipse的
Help > About Eclipse SDK > Installation Details, 選擇不再需要的plugin,
然後點選uninstall,就可以移除掉這些plugins.


FAQ How do I remove a plug-in?

2012年4月27日 星期五

新竹市金山街套房出租

金山街舒適大套房出租,有瓦斯鍋爐, 室內晒衣場, 機車停車場,電視,網路,第四台,
專人清潔公共空間,倒垃圾,代收郵件,
月租金6500,
意者洽:03-5632658, 吳先生

另有安康社區(近光復路商圈,生活機能便利)套房出租,一般住宅區,很安靜,家電配備齊全,
租金6000,意者洽,0920-238-669,田先生.

此為版主代友發文

2012年4月26日 星期四

Android-activity筆記

Activity,
1.可以視為應用程式的活動空間, 相當於main method.
2.採用Last in, first out 的back stack機制. 也就是說使用者目前的應用程式放在最上方,暫時沒用到的程式會放在堆疊的下方.

Activity的三種狀態:

Resumed :可恢復的,可想像成使用者正在操作執行中的意思.
Paused: 暫停的,雖然還在前景,可以給使用者看到,但使用者目前並沒有在操作.
Stopped: Activity被放到背景,使用者看不到,雖然還是處於活著的狀態,但當作業系統需要記憶體時,隨時有可能被回收掉.

參考網頁

Android 專有名詞縮寫整理

AVD = Android virtual devices ; android虛擬裝置.
ADT = Android Development Tools; 也就是所謂的sdk,用來開發在android手機上的應用程式.
APK = Application package file.
DEX = Android 的 byte code的附檔名. class是Java byte code的附檔名 DIP = Density-independent pixel , 相對應的單位為dp. 因此android建議在定義圖片像素時要以dp為單位 DPI = dots per inch, 用來形容screen像素在每一inch的點數, 也就是螢幕解析度.

2012年4月14日 星期六

取消Eclipse Syntax Validation(參數驗證)

Windows-->Preferences-->Validations
You can deselect all entries that you don't want to validate.

2012年4月9日 星期一

Java 靜態初始化區塊(Static initialization block)

When you want to initialize a static or instance variable in a more complicated way, you can use block to achieve this goal.
public class StaticInitBlockDemo {

static double[] arra = null;
static {
int size = 5;
array = new double[size];
for (int i = 0; i < array.length; i++) {
array[i] = Math.random();
}
}

public static void main(String[] args){
for(int i =0 ;i<array.length;i++ ){
System.out.println(array[i]);
}
}
}


Static Variable

2012年4月2日 星期一

Design pattern - Java creation method


public class CreationMethod {

public static void main(String [] args){
Student s1 = Student.createInstance(1);
Student s2 = Student.createInstance(1, "hello");
System.out.println(s1.toString());
System.out.println(s2.toString());
}
}

class Student{
int id;
String name;
private Student(int id){
this.id = id;
}

private Student(int id, String name){
this.id = id;
this.name = name;
}

public static Student createInstance(int id , String name){
return new Student(id,name);
}

public static Student createInstance(int id){
return new Student(id);
}

public String toString(){
return id+": "+name;
}
}

2012年3月29日 星期四

Html-margin , border, padding

margin: 元件本身和其他元件之間的空間
border: 填滿元件本身的邊界
padding: 填滿元件內容到元件邊界之間的空間.

2012年3月27日 星期二

CSS line-height usage

This property can align the text within a input tag






style='left: 210; top: 22; width: 110; line-height: 54px; height: 54; font-size: 36;' />




2012年3月26日 星期一

Java Static Variable


public class StaticVariableTest {

public static void main(String []args){
Student s1 = new Student();
Student.height =1;
Student s2 = new Student();
Student.height =2;
System.out.println(Student.height);
}

}

class Student{
static int height;
}

Java ArrayList


public class ArrayListDemo {

public static void main(String[] args) {
/**
* Following example will cause a run time exception:
* java.lang.ClassCastException, although no compilation error happened.
*/

/*
* int sum = 0;
* ArrayList al = new ArrayList();
* al.add("1");
* al.add(new Integer(2));
* for (int i = 0; i < al.size(); i++) {
* sum+= (Integer)al.get(i);
* }
* System.out.println(sum);
*/

/**
* Following example will fix above problem.
*/
int sum = 0;
ArrayList al = new ArrayList();
// al.add("1"); this line has a compilation error.
al.add(new Integer(1));
al.add(new Integer(2));
for (int i = 0; i < al.size(); i++) {
sum += (Integer) al.get(i);
}
System.out.println(sum);
}

}

2012年3月25日 星期日

Merge Sort (合併排序法)


package sort;

public class MergeSortDemo {


public static void main(String[] args) {
int[] array = { 3, 3,2,1,0,4,5,1,4};
array = mergeSort(array);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}

public static int[] mergeSort(int[] list) {
//if merely left 1 element return list;
if (list.length <= 1) {
return list;
} else {
int[] left;
int[] right;
int middle = list.length / 2;
//declare left sub array;
left = new int[middle];
//declare right sub array;
right = new int[list.length - middle];
int j = 0;
for (int i = 0; i < list.length; i++) {
if (i < left.length) {
//initialize left array
left[i] = list[i];
} else {
//initialize right array
right[j] = list[i];
j++;
}
}
//divide left array into small parts;
left = mergeSort(left);
//divide right array into small parts;
right = mergeSort(right);
//combine small parts of left and right
return merge(left, right);
}
}

public static int[] merge(int[] left, int[] right) {
int[] result = new int[left.length + right.length];
int j = 0;
while (left.length > 0 || right.length > 0) {
//left and right array have elements.
if (left.length > 0 && right.length > 0) {
if (left[0] <= right[0]) {
result[j] = left[0];
left = shiftArray(left);
} else {
result[j] = right[0];
right = shiftArray(right);
}

} else if (left.length > 0) {
//left array has elements;
result[j] = left[0];
left = shiftArray(left);
} else if (right.length > 0) {
//right array has elements;
result[j] = right[0];
right = shiftArray(right);
}
j++;
}
return result;
}

private static int[] shiftArray(int[] i) {
int[] result = new int[i.length - 1];
for (int j = 0; j < result.length; j++) {
result[j] = i[j+1];
}
return result;
}
}




Reference Wiki

2012年3月24日 星期六

Recursive Selection Sort (遞迴選擇排序法)

維護舊有Java程式專案
1:  public class RecursiveSelectionSort {  
2:      public static void main(String[] args) {  
3:          int [] array ={5,2,3,6,1,7,0,9,100,4,8};  
4:          selectionSort(array, array.length);  
5:          for(int i=0;i<array.length;i++){  
6:              System.out.print(array[i]+" ");  
7:          }  
8:      }  
9:      /**  
10:       * Using the concept of selection sort.  
11:       * Implemented by an iterative and a recursive mechanisms.  
12:       *   
13:       * Following are steps:  
14:       * 1.Finding the smallest one and its index;  
15:       * 2.Put the smallest into the right end side;  
16:       * 3.Decrease the array size;  
17:       * Recursively calling this method.  
18:       *   
19:       * @param array unsorted array  
20:       * @param length array length  
21:       */  
22:      public static void selectionSort(int[] array , int length) {  
23:          if(length > 0){  
24:              int smallestIdx = 0 ;  
25:              int smallest = array[smallestIdx];  
26:              //1.From left to right find the smallest one and its index;  
27:              for(int i =0 ;i<length ;i++){  
28:                  if(array[i]< smallest){  
29:                      smallest = array[i];  
30:                      smallestIdx = i;  
31:                  }  
32:              }  
33:              //2.Put the smallest into the right end side;  
34:              swapElements(array,smallestIdx,length -1);  
35:              //3.Decrease the array size;  
36:              length -=1;  
37:              //4.Recursively calling this method.  
38:              selectionSort(array,length);  
39:          }  
40:      }  
41:      private static void swapElements(int[] array, int idx, int idx1) {  
42:          int tmp = array[idx];  
43:          array[idx] = array[idx1];  
44:          array[idx1] = tmp;  
45:      }  
46:  }  

一中兩區

一中兩區?? 統一不是壞事, 如果跟民主國家統一那沒問題,

要跟共產國家統一??請舉辦公投,如果通過的話,就統一好了,

再這樣下去,會真的成為馬區長.!!

最好是維持現狀,等待中國成為民主國家再說

2012年3月23日 星期五

Binary Search (Recursive version)

Before you do binary search, you should sort the unsorted elements first 在使用binary搜尋之前, 要先把資料排序過. Sort(排序)

public class BinarySearch {
 
 public static void main(String [] args){
  int [] i ={2,3,4,4,5,6,7,87};
  System.out.println(binarySearch(i,0,i.length-1,5));
  
 }
 
 public static int binarySearch(int[] i, int left, int right, int target) {
  int middle = (left+right)/2;
  if (i[middle] == target) {
   return middle;
  } else if (i[middle] > target) {
   return binarySearch(i,left,middle,target);
  } else{
   return binarySearch(i,middle,right,target);
  }
 }
}



A c++ binary search tree

Iterative and Recursive

2012年3月17日 星期六

Java Inner Class(內部類別)


public class InnerClassDemo {

class Student{
void print(){
System.out.println("This is an inner class as an instance variable");
}
}

void classInAmethod(){
class Son{
void print(){
System.out.println("I am within a method");
}
}
Son s = new Son();
s.print();
}

public static void main(String[]args){
InnerClassDemo is = new InnerClassDemo();
is.classInAmethod();
InnerClassDemo.Student s = is.new Student();
s.print();
}

}


資料來源:http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
相關文章:anonymous class

你真的是一個programmer嗎??

光會if-else, for or while loop, call 3rd party library, or 知道常用的framework, 對於programmer 來說, 以上只是必須的基本技巧, 嚴格來說要能實做出各種演算法,才能說自己會寫程式.

Java 變數指定


import java.util.ArrayList;

public class VariableAssignDemo {

public static void main(String[] args){
ArrayList a1 = new ArrayList();
a1.add(1);
/**
* Following case assigns object reference to a new variable
*/
ArrayList a2 =a1;
a2.add(2);
System.out.println(a1.toString());
System.out.println(a2.toString());

System.out.println("-------------------");

/**
* Following is a deep copy , all elements are included..
* If you want to keep original object , but do some changes on it.
* A deep copy is a solution.
*/
ArrayList a4 =new ArrayList();
for(int i = 0 ;i < a1.size() ;i++){
a4.add(a1.get(i));
}
a1.remove(0);
System.out.println(a1.toString());
System.out.println(a4.toString());

}
}

Java method override


public class OverwriteDemo {

}

class Father{

void print(){

}
}

class Son extends Father{

// compile-error
// private void print(){
// }

protected void print(){

}
}

2012年3月12日 星期一

Java Properties


 import java.io.*;  
import java.util.Properties;
public class PropertiesDemo {
/**
* File Name: some.prop
* Content : msg= Hello World.
*/
public static void main(String[] args) throws IOException {
// First you must create a file named "some.prop" then choose it .
FileInputStream fis = new FileInputStream("some.prop");
Properties prop = new Properties();
prop.load(fis); // Load properties from file input stream
String meesage = (String) prop.get("msg"); // get entry key
System.out.println(meesage);// print it out
prop.setProperty("msg", "modified Hello World");// add or modify new properties.
FileOutputStream fos = new FileOutputStream("some.prop");// Get property source file again.
prop.store(fos, "modified propery file");// Save the newest contents into the property file
prop.list(System.out);// List them out.
}
}


相關連結:
http://goodideascome.blogspot.com/2011/12/spring-ioc-with-hello-world-example.html

2012年3月11日 星期日

Java exception -例外處理

Runtime exception: 非程式設計師所能預期到的錯誤.可直接拋出.

如果類似檔案找不到 ,這種可預期的錯誤狀況便要利用

try ..catch 把錯誤接收起來並做適當的處理

import java.io.*; 
public class ExceptionDemo {
public static void main(String[] args) throws FileNotFoundException{
int i =Integer.parseInt("r"); // this is a runtime exception
System.out.println(i);
//using a try catch block to catch checked exception
try {
FileReader fr = new FileReader(new File("xxx.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//or throw out this exception to the caller.
FileReader fr = new FileReader(new File("xxx.txt"));
}
}



Following is a fail case.



public class UnreachableDemo {
public static void main(String[] args){
int [] k =new int []{1,2,3};
for(int i = 0 ; i < k.length+1 ; i++ ){
System.out.println(k[i]);
}
System.out.println("arrive here?");
}
}




Following is a success case.




public class ReachableDemo {
public static void main(String[] args){
int [] k =new int []{1,2,3};
try{
for(int i = 0 ; i < k.length+1 ; i++ ){
System.out.println(k[i]);
}
System.out.println("within a try block , so it is unreachable");
}catch(Exception e){
e.printStackTrace();
}
System.out.println("outside");
}
}

Java action listener

Inner Class implementation:



Change getHelloButton with follwing example, you will get an anonymous version implementation:

2012年3月10日 星期六

Java 物件比較

因為底下這兩個物件都有相同的記憶體位址,所以都是true.

如果equals方法,有被覆寫過的話,那麼hashCode方法也需要被覆寫, 以確保物件的相同.


Java 物件equals method 的用法

什麼是unicode?

unicode是一種字元編碼的方式,
每一個字元無論在哪一種作業系統平台,或程式語言都只有一個唯一utf的號碼.

下面這個例子是寫入中文, 然後用英文編碼讀取, 所以會讀出亂碼.


若寫入和讀出都是使用unicode的話,就可以正常顯示.

JSP 標籤函式庫

uri :此函式庫的位址.
prefix : 如果有引用很多tag library的話,可以用來區別各個不同的函式庫的名稱.

SCWCD 考試目標 :JSP技術-1

被包覆在out.println()可列印出來的部分,還有網頁本身的文字都算是template text.



scripting elements (comments, directives, declarations, scriptlets, and expressions)

comments: 註解


directives: 指令,jsp有三種指令: page , include , taglib


declarations: 變數宣告


scriptlet: 一般Java的程式碼


expressions: 描述

2012年3月9日 星期五

2012年3月8日 星期四

Java thread(執行緒)

Java 物件轉型

Animal ani = new Dog();
隱性轉型,此時的ani變數只可使用Animal類別提供的方法,
無法使用Dog類別的方法.
(可以大容器裝小物件)

Dog dg1 = new Animal();
(小容器裝大物件,會產生編譯錯誤)

Dog dg2 = (Dog)ani;
明確轉型,此時我們指定animal就是dog.
這是多型的用法,假如有一個cat類別也繼承animal,
也可轉型為cat來使用.

如果不確定執行時期的物件是哪一個類別的實體,
可以使用instanceOf這個方法來判斷,以避免丟出

Java 字元編碼轉換

native2ascii 欲轉換的中文字

會印出unicode版本的資源編碼.


2012年3月4日 星期日

Java Serialization (Java 序列化)

一般來說物件實體只能存活在JVM中如果想要把物件的實體狀態給保留下來的話,可以使用序列化這個技術,以下是把物件實體寫入檔案的例子.





而SerializationReadSample.java則是把剛剛序列化後的物件,讀回來的程式碼:


只要欲保存的類別有implement Serializable這個界面, 就可以拿來作序列化的動作.

當類別中有不想被序列化的field, 例如,socket, or thread等等的動態內容,

則可以在宣告變數的時候加上transient 這個關鍵字.


千萬不可序列化內部類別(inner class) , 無論是local或是匿名內部類別. 因為這麼做的話 ,

compiler會為內部類別產生合成的建構子.  因為合成的建構子 , 在source code找不到實作的細節

會隨著java compiler版本的不同, 而產生不同的建構子, 也就是說你在A版本編譯出來的code,

很可能在B版本跑不起來 , 造成相容性的問題 .

2012年3月1日 星期四

容錯(Fail-over support)和負載平衡(Load Balancing)

容錯: 當一台server無法服務客戶端的請求時, 其他的server可以立刻把所有的服務請求接收過來執行.

負載平衡: server會把客戶端請求,分配給目前工作loading較不重的server來執行.

2012年2月28日 星期二

Servlet RequestDispatcher (Servlet請求分配介面)

接收來自Client的請求, 然後分派給在server上的其他資源,例如 html, servlet, jsp 等.

這個interface有兩個方法 :

1.forward : 這個方法允許一個servlet先做初步處理, 然後交給另一個servlet產生結果. 要注意的地方是這方法必須在使用者端的請求被commit前呼叫, 否則會丟出IllegalStateException.

2.include : 引入其他在ServletResponse裡的資源(Servlet, Jsp ,Html), 基本上可以視為是一種server-side的include. 被引入的servlet 不能夠改變回應的狀態碼(Response status code),也不能設定headers.任何嘗試改變屬性的行為都會被忽略掉.


ServletContext 和 ServletRequest 介面都可以獲得request dispatcher介面.







參考自:

2012年2月27日 星期一

Dynamic Programming(動態程式規劃)

Dynamic Programming : 主要概念是把複雜的大問題,切割成多個小問題,然後把這些小問題的答案組合出一個較完成的答案, 來解答大問題. 若列舉出所有答案的排列組合,很花時間而且會做很多多餘且重複不必要的計算, 使用動態程式設計可以減少許多不必要的計算時間和次數.

以下用找出陣列元素總合為最大值的子陣列來做解釋

Maximum Subarray Problem:






2012年2月26日 星期日

Hello World Servlet Examples (範例)

首先在tomcat webapps底下建立這個目錄結構:

















HelloWorldServlet.java



index.html



web.xml


相關連結

Hello World JSP 範例

在tomcat的webapps這個目錄底下, 建立如下的目錄結構:

目錄結構:










HelloWorldJSP.jsp





index.html



或是說也可以使用Java Bean的方式來達成此項功能.


UseBeanHello.jsp(放在根目錄)



HelloWorldBean.java (放置此檔的.class在WEB-INF/classes目錄底下.)


相關參考連結: