總網頁瀏覽量

2011年12月30日 星期五

16章 多執行緒

16章 多執行緒

start()
進入待命狀態 可執行狀態

run()
執行狀態

wait()
進入等待狀態

notify()
讓某個等待中的執行緒回到待命狀態

notifyAll()
讓該物件的所有等待的執行緒 回到待命狀態

interrupt()
設定該執行緒的中斷旗標 拋出例外

sleep()單位毫秒
使執行緒進入休眠狀態 休眠時間到後回到待命狀態

join()
結合兩個執行緒

設置優先權:
Thread.MIN_PRIORITY 1
Thread.MAX_PRIORITY 10
Thread.NORM_PRIORITY 5

setPriority()
getPriority()
yield() 讓其他執行緒有執行的機會

Thread.currentThread().getName() 取得目前執行執行緒的名稱


參考: http://programming.im.ncnu.edu.tw/J_index.html

繼承Thread寫法
public class ThreadExample1 extends Thread {
 public void run() { // override Thread's run()
  System.out.println("Here is the starting point of Thread.");
  for (;;) { // infinite loop to print message
  System.out.println("User Created Thread");
  }
 }
 public static void main(String[] argv) {
  Thread t = new ThreadExample1(); // 產生Thread物件
  t.start(); // 開始執行t.run()
  for (;;) {
   System.out.println("Main Thread");
  }
 }
}

實現Runnable介面寫法
public class ThreadExample2 implements Runnable {
	public void run() { // implements Runnable run()
		System.out.println("Here is the starting point of Thread.");
		for (;;) { // infinite loop to print message
		System.out.println("User Created Thread");
		}
	}
	public static void main(String[] argv) {
		Thread t = new Thread(new ThreadExample2()); // 產生Thread物件
		t.start(); // 開始執行Runnable.run();
		for (;;) {
		System.out.println("Main Thread");
		}
	}
}








15章 例外處理

15章  例外處理

Exception extends Throwable
Throwable extends Object

Integer.parseInt方法: 將字串轉成int數值

public void fun() throws Exception{
    try{
  
    }
    catch(Exception e){
        throw e;
    }
    finally{
  
    }
}

toString()以簡單的字串描述該例外
getMessage()列出細節訊息
printStackTrace()將堆疊資訊印在螢幕上,可幫助設計者快速找到錯誤點

2011年12月26日 星期一

JAVA 基礎物件導向

JAVA 環境變數:
JAVA_HOME=F:\jdk1.6.0_01
path=%JAVA_HOME%\bin;%path%
%path%:動態獲取path環境變數的值。
%JAVA_HOME%:動態獲取名稱為JAVA_HOME環境變數的值。


基本型別:
char
2
0 ~ 255
byte
8
-128 ~ 127
short
16
-32768 ~ 32767
int
32
-2147483648 ~ 2147483647
float
32
-3.4E38(-3.4*10^38) ~ 3.4E38(-3.4*10^38)
double
64
-1.7E308(-1.7*10^308) ~ 1.7E308(-3.4*10^308)
long
64
-9223372036854775808 ~ 9223372036854775807



變數初值:
class內的資料成員具有預設值,但在區域變數的變數就沒有預設值,需要定義初值後編譯才會通過

建構子可以接受引數,但是不能傳回值。建構子和方法之間最重要的不同處,就是建構子不能指定傳回值的型別(void都不行)

static成員只有一個副本可供類別所有物件共同使用,static就是類別所擁有而不是物件。宣告為static的方法不可以存取non-static類別成員,並且沒有this參照

Final指定不可更改變數(意指常數)
Private final int INCREMENT = 5;

super.fun() 表示明顯地使用呼叫父類別建構子語法

“is-a”用來表示繼承,一個子類別的物件也就是其父類別物件

父類別: A, 子類別:B
A a = new A();
B b = new B();
A a1 = b;

子類別物件的參照b指定給父類別型別變數a1
含有指向子類別物件參照的父類別型別變數會叫用子類別的方法

抽象類別:
抽象類別就是作為繼承階層中的父類別,抽象方法的類別必須宣告為抽象類別,而繼承自抽象父類別的每個子類別,必須提供父類別抽象方法的實作部分。
抽象類別不可實體化一個物件

Instanceof: 來判定每個物件的型別是否相容於此型別
向下轉型必須是該物件與要轉型的物件存在有is-a的關係

介面:
若要使用介面時,類別必須指明會實作出這個介面,且必須重新宣告介面的每個方法,如果類別未實作介面的任何方法時,則該類別就是抽象類別,且必須宣告為abstract。介面中所有的方法必須是public以及abstract。使用介面的好處在於類別可以實作多個介面而不是一個。

內部類別物件可以存取外部類別物件的所有變數和方法。
匿名內部類別是指不具名稱的內部類別,且宣告於程式中該內部類別物件建立的地方。





2011年12月25日 星期日

The import android cannot be resolved 錯誤

import功能加入專案,出現The import android cannot be resolved的錯誤

修改在project --> Properties --> Android中的Project Build Target選相應的SDK

或在
default.properties文件 target=android-XX  改成相應的版本

2011年12月23日 星期五


Activity02 à OtherActivity 的設計流程
目標: 點擊按鈕後 顯示另一個Activity

1.      Main.xmlbutton  id width height
2.      Activity02使用findViewById 找到id 來使用(Button)
3.      新增OtherActivity.javaother.xml  也要在Activity_02.Manifest內註冊(namelabel)
4.      other.xml內加入TextView id width height
5.      OtherActivity.java 使用findViewById 找到id 來使用(TextView)
6.      strings.xml 設計name與值 在回OtherActivity.java來使用 myTextView.setText setContentView
7.      開始設計listener監聽器 先實作OnClickListener
8.      建立Intent物件  使用setClass函式來表示 從哪個Activity 到哪個Activity
9.      使用startActivity(intent)來啟動監聽器  同時設計Button要綁住監聽器


Activity02設計傳入資料 intent.putExtra(“key”, “value”);
OtherActivity內接收資料 
Intent intent = getIntent();
String value = intent.getStringExtra(傳入的keyName);
設置myTextView.setText(傳入的value);

也可以啟動不同應用層 發訊息的範例
Uri uri = Uri.parse("smsto://0800000123");   
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);   
intent.putExtra("sms_body", "The SMS text");   
startActivity(intent);

2011年12月12日 星期一


小瑪莉程式
利用c#實作一個介面的小遊戲,同時也運用了物件導向的概念,算是有了解到OO的類別實作,從C語言跳到C#的實作方式,有蠻大的不同,然而要設計一個好類別更是需要不少的經驗,學習寫介面算是不錯的興趣,比較有個實體的感覺。也想問問有人會寫讓圖片振動的效果嗎??

執行畫面



















開始後圖片會以輪流消失的方式來增加動態的感覺,也可以學習一些C# IDE上的工具來設計介面

程式碼
 Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Little_Mary
{
    public partial class Form1 : Form
    {
        private Player player;
        private Game[] game;
        private int betmoney;
        public int number = 1;
        public bool gamestart = true;

        public Form1()
        {
            InitializeComponent();
            Random myRandomizer = new Random();
           
            game = new Game[7]{
                new Game() {MyRandom = myRandomizer, MyPictureBox = pictureBox1, MyTextBox = odds1, Odd = 0},
                new Game() {MyRandom = myRandomizer, MyPictureBox = pictureBox2, MyTextBox = odds2, Odd = 0},
                new Game() {MyRandom = myRandomizer, MyPictureBox = pictureBox3, MyTextBox = odds3, Odd = 0},
                new Game() {MyRandom = myRandomizer, MyPictureBox = pictureBox4, MyTextBox = odds4, Odd = 0},
                new Game() {MyRandom = myRandomizer, MyPictureBox = pictureBox5, MyTextBox = odds5, Odd = 0},
                new Game() {MyRandom = myRandomizer, MyPictureBox = pictureBox6, MyTextBox = odds6, Odd = 0},
                new Game() {MyRandom = myRandomizer, MyPictureBox = pictureBox7, MyTextBox = odds7, Odd = 0},
            };

            player = new Player() { Cash = 300 };
            OddProduct();

            int Playmoney = 0;
            playmoney.Text = "$" + Playmoney;
            cash.Text = "$" + player.Cash;
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
/*賭注單位*/
        {
            betmoney = (int)numericUpDown1.Value;
        }

        private void bet_Click(object sender, EventArgs e)/*下注資訊*/
        {
            betmoney = (int)numericUpDown1.Value;
            gamestart = false;
            UpdateGame(gamestart);

            if (player.Cash >= betmoney * 10)
            {
                playmoney.Text = "$" + betmoney * 10;
                player.Cash -= betmoney * 10;
                cash.Text = "$" + player.Cash;
            }
            else
            {
                MessageBox.Show("You have not enough money!!!");
                start.Enabled = false;
            }
        }

        private void rb_CheckedChanged(object sender, EventArgs e)/*判斷玩家選幾號*/
        {
            for (int i = 1; i < 7; i++)
            {
                if (radioButton1.Checked == true)
                {
                    number = 1;
                }
                else if (radioButton2.Checked == true)
                {
                    number = 2;
                }
                else if (radioButton3.Checked == true)
                {
                    number = 3;
                }
                else if (radioButton4.Checked == true)
                {
                    number = 4;
                }
                else if (radioButton5.Checked == true)
                {
                    number = 5;
                }
                else if (radioButton6.Checked == true)
                {
                    number = 6;
                }
                else if (radioButton7.Checked == true)
                {
                    number = 7;
                }
             }

        }
       
        private void start_Click(object sender, EventArgs e)/*開始*/
        {
            int count = 2;
            while (count != 0)
            {
                for (int i = 0; i < 7; i++)
                {
                    game[i].MyPictureBox.Visible = false;
                    System.Threading.Thread.Sleep(125);
                    Application.DoEvents();
                }

                for (int i = 0; i < 7; i++)
                {
                    game[i].MyPictureBox.Visible = true;
                    System.Threading.Thread.Sleep(125);
                    Application.DoEvents();
                }
                count--;
            }

            int winner = player.MyGame.Run();
            MessageBox.Show("The winner number is " + winner);

            if (winner == number)
            {
                player.Cash += betmoney * 10 * game[number - 1].Odd;
                MessageBox.Show("You win " + betmoney * 10 * game[number - 1].Odd + " dollars");
            }
            else
            {
                MessageBox.Show("You are lost");
            }
            gamestart = true;
            UpdateGame(gamestart);
            OddProduct();
            cash.Text = "$" + player.Cash;
            playmoney.Text = "$";

        }

        private void UpdateGame(bool gamestart)
        {
            bet.Enabled = gamestart;
            radioButton1.Enabled = gamestart;
            radioButton2.Enabled = gamestart;
            radioButton3.Enabled = gamestart;
            radioButton4.Enabled = gamestart;
            radioButton5.Enabled = gamestart;
            radioButton6.Enabled = gamestart;
            radioButton7.Enabled = gamestart;     
        }

        private void OddProduct()
        {
            for (int i = 0; i < 7; i++)
            {
                game[i].Odd = player.MyGame.Odds();
                game[i].MyTextBox.Text = game[i].Odd.ToString();
            }
        }
    }
}


Game.cs
namespace Little_Mary
{
    public class Game
    {
        public Random MyRandom;
        public PictureBox MyPictureBox = null;
        public TextBox MyTextBox = null;
        public int Odd;
       
        public Game()
        {
            MyRandom = new Random();
            MyPictureBox = new PictureBox();
            MyTextBox = new TextBox();
        }

        public int Odds()
        {
            int odds = MyRandom.Next(2, 6);
            MyTextBox.Text = odds.ToString();
            return odds;
        }

        public int Run()
        {
            int winNumber = MyRandom.Next(1, 8);
            return winNumber;
        }
    }
}

Play.cs

namespace Little_Mary
{
    public class Player
    {
        public int Cash;
        public Game MyGame;
        public Random MyRandom;

        public Player()
        {
            MyGame = new Game();
            MyRandom = new Random();
        }
    }
}

現在網路上很多都有提供電影字幕或是連續劇字幕的資源,也有不少學習英文的人喜歡邊看影片邊練習英聽或是會話,所以這個程式運用在練習中英閱讀及會話方面,透過隨手可得的字幕檔後,將其合併來練習。當中可練習不少開關檔案的語法,及思考排版的設計,在程式中用了4stream來協助讀檔與寫檔。

執行內容及結果
英文字幕檔內容
1
00:03:27,600 --> 00:03:28,400
Little girl?

2
00:03:30,900 --> 00:03:31,700
I'm a policeman.

3
00:03:32,700 --> 00:03:33,500
Little girl.

4
00:03:38,600 --> 00:03:39,700
Don't be afraid.

中文字幕檔內容
1
00:03:27,600 --> 00:03:28,400
小姑娘?

2
00:03:30,900 --> 00:03:31,700
我是警察

3
00:03:32,700 --> 00:03:33,500
小姑娘

4
00:03:38,600 --> 00:03:39,700
別害怕

合併中英字幕結果
Little girl?
小姑娘?

I'm a policeman.
我是警察

Little girl.
小姑娘

Don't be afraid.
別害怕

Little girl.
小姑娘

//中英字幕合併By Cheng yu-zheng
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>


FILE *stream_eng, *check_eng, *stream_cht, *check_cht, *write_data;
char checkString1[100], writeString1[100], checkString2[100], writeString2[100];
int counter_eng = 2, counter_cht = 2;
int flag_eng = 0, flag_cht = 0;

void write_eng(char checkString1[], FILE *check_eng, FILE *stream_eng, FILE *write_data, FILE *check_cht, FILE *stream_cht);
int call_print(FILE *stream_eng,  FILE *write_data);
void write_cht(char checkString2[], FILE *check_cht);
int call_print_cht(FILE *stream_cht,  FILE *write_data);

int main(void)
{
        stream_eng = fopen("eng1.txt", "r");
        check_eng = fopen("eng1.txt", "r");
        stream_cht = fopen("cht1.txt", "r");
        check_cht = fopen("cht1.txt", "r");
        write_data = fopen("text.txt", "w");

        if(stream_eng == NULL || stream_cht == NULL || check_eng == NULL ||  check_cht == NULL || write_data == NULL)
        {
                printf("開始檔案失敗, 請將正確檔案放入資料夾內");
        }
        else
        {
                write_eng(checkString1, check_eng, stream_eng, write_data, check_cht, stream_eng);
        }
        fclose(stream_eng);
        fclose(check_eng);
        fclose(stream_cht);
        fclose(check_cht);
        fclose(write_data);
}

void write_eng(char checkString1[], FILE *check_eng, FILE *stream_eng, FILE *write_data, FILE *check_cht, FILE *stream_cht)
{
        while(fgets(checkString1, 100, check_eng) != NULL){
                while(checkString1[3] != ':' && atoi(checkString1) == counter_eng){
                        flag_eng = call_print(stream_eng, write_data);
                        if(flag_eng == 1){
                                counter_eng++;
                                if(counter_eng >= counter_cht)
                                        write_cht(writeString2, check_cht);
                        }
                }
        }
}

int call_print(FILE *stream_eng, FILE *write_data)
{
        while(fgets(writeString1, 100, stream_eng) != NULL){
                int stop_flag = 0;
                if(writeString1[2] != ':' && (isdigit(writeString1[0]) == 0 || strlen(writeString1) >=5) && writeString1[0] != '\n'){
                        fputs(writeString1, write_data);
                }

                if(atoi(writeString1) == counter_eng){
                        return stop_flag = 1;
                }
        }
        return 0;
}

void write_cht(char checkString2[], FILE *check_cht)
{
        int gobackto_eng = 0;
        while(fgets(checkString2, 100, check_cht) != NULL &&  gobackto_eng == 0){
                while(checkString2[3] != ':' &&  gobackto_eng == 0 && (( 0 <= checkString2[0] <= 127) ? atoi(checkString2) == counter_cht : 0)){
                        flag_cht = call_print_cht(stream_cht, write_data);
                        if(flag_cht == 1){
                                counter_cht++;
                                if(counter_cht == counter_eng)
                                        gobackto_eng = 1;  
                        }
                }
        }     
}

int call_print_cht(FILE *stream_cht, FILE *write_data)
{
        char temp[] = "\n";
        while(fgets(writeString2, 100, stream_cht) != NULL){
                int stop_flag = 0;
                if(writeString2[2] != ':' && strlen(writeString2) >=5){
                        fputs(writeString2, write_data);
                }

                if(atoi(writeString2) == counter_cht){
                        fputs(temp, write_data);
                        return stop_flag = 1;
                }
        }
        return 0;
}