搜尋此網誌

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?