標籤

二元樹 (1) 字串常數池 (1) 投資 (3) 每月損益 (37) 例外處理 (1) 泛型 (2) 股票 (15) 指標 (5) 英文 (8) 基本資料型別 (1) 期貨 (1) 程式交易 (10) 量化投資 (5) 亂亂寫 (3) 概念 (3) 資料結構 (3) 演算法 (3) 數學 (3) 轉型 (1) AMA (1) ArrayList (1) assert (1) BeautifulSoup (1) C/C++ (8) casting (1) ClassCastException (1) classpath (1) Collection (4) Comparable (1) comparTo() (1) constructor (1) database (3) Debian (1) Dropbox (2) EA (2) enum (1) equals() (2) exception (3) extends (1) ffmpeg (1) final (1) Git (1) HashMap (1) HashSet (1) hasNext() (1) HTS (3) instanceof (1) IS-A (1) Iterator (1) JAVA (43) length (1) Linux (31) List (1) Mac (6) Map (1) ML (2) MT4 (6) MySQL (2) next() (1) NullPointerException (1) Number (1) Numpy (2) OpenCart (1) OpenCV (3) OSX (1) overloading (1) overriding (3) pandas (2) PHP (8) PriorityQueue (1) Python (11) Queue (1) random() (1) reverse() (1) Samba (1) SCJP (21) sqrt() (1) synchronized (1) talib (1) ufw (1) uTorrent (1) var-args (2) VHF (1) vim (2) Yhoo知識+ (4)

2012年12月8日 星期六

linux重灌後無法ssh

linux重灌後發現ssh產生錯誤:


@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
76:bd:e0:e9:c2:13:6d:ca:d8:eb:b2:a8:58:9b:4b:b6.
Please contact your system administrator.
Add correct host key in /Users/superppp/.ssh/known_hosts to get rid of this message.
Offending key in /Users/superppp/.ssh/known_hosts:1
RSA host key for 192.168.1.101 has changed and you have requested strict checking.
Host key verification failed.

解決方式:

$ ssh-keygen -R 192.168.1.101
/Users/superppp/.ssh/known_hosts updated.
Original contents retained as /Users/superppp/.ssh/known_hosts.old

參考自這裡


linux新增使用者帳密

#useradd Name 
#passwd Name

2012年12月7日 星期五

三維陣列走訪

試撰寫一程式,請利用三維列陣A完成下列題目的要求。列陣A的值如下
int A[][][]={{{15,50,65},{38,94,25},
{79,44,19},{89,54,73}},
    {{14,90,46},{43,23,67},
{32,56,78},{94,78,40}}};

(a)請印出陣列內容。
(b)在陣列A裡找出所有大於等於50的元素,將該元素重新設值為99。
(c)印出完成(b)之後的陣列內容。


--------------------------------------

public class Array99{
public static void main(String[] args){
int[][][] A={{{15,50,65},{38,94,25},{79,44,19},{89,54,73}},
    {{14,90,46},{43,23,67},{32,56,78},{94,78,40}}};
    showArray(A);
    showArray(A);
}
public static void showArray(int[][][] a){
for(int i=0; i<a.length; i++){
for(int j=0; j<a[0].length; j++){
for(int k=0; k<a[0][0].length; k++){
System.out.print(a[i][j][k]+ " ");
if(a[i][j][k]>=50) a[i][j][k] = 99;
}
System.out.println();
}
}
System.out.println();
}
}

補充:其實for迴圈那裡用for-each會比較好理解,如for(int[][] b: a)...for(int[] c: b)...for(int d: c),不過這樣就不能指派值了。

好啦,還是補一下for-each的版本:

public class Array99{
public static void main(String[] args){
int[][][] A={{{15,50,65},{38,94,25},{79,44,19},{89,54,73}},
    {{14,90,46},{43,23,67},{32,56,78},{94,78,40}}};
    showArray(A);
    showArray(A);
}
public static void showArray(int[][][] a){
for(int[][] i: a){
for(int[] j: i){
for(int k=0; k<j.length; k++){     //這裡如果用for(int k: j)會無法指派值
System.out.print(j[k]+ " ");
if(j[k]>=50) j[k] = 99;
}
System.out.println();
}
}
System.out.println();
}
}

Euler的圓周率


public class Pi{
public static void main(String[] args){
System.out.println("Euler(10)=" +Euler(10));
System.out.println("Euler(100)=" +Euler(100));
System.out.println("Euler(1000)=" +Euler(1000));
}
public static double Euler(int n){
boolean isPrime;
double sum = 1.0;
int count = 0;
int i = 3;
while(count < n){
isPrime = true;
for(int j=3; j<=Math.sqrt(i); j+=2){
if(i%j == 0){
isPrime = false; break;
}
}
if(isPrime){
if((i-1)%4 == 0) sum *= i / (double)(i+1);
else sum *= i / (double)(i-1);
count++;
}
i += 2;
}
return sum * 2;
}
}

數字反轉


請利用eclipse打一支程式
題目如下:
實作一個public static int reverse(int n)方法, 將一個5位數的數字逆轉. EX: 呼叫 reverse(12345) 會得到一個 54321 的結果. (提示: 可利用求餘數的方法將五個數字分別切割出來, 然後再逆轉組合. 12345 % 10 = 5)

PS:用method做

-----------------------------------

public class ReverseNum{
public static int reverse(int n){
String wn = "";
wn += n;
StringBuilder sbd = new StringBuilder(wn);
sbd.reverse();
return Integer.parseInt(sbd.toString());
}
public static void main(String[] args){
System.out.println(reverse(12345));
}
}


Java的樂透問題


拜託在後面寫一下解釋~謝謝
1.
請設計一個程式會進行樂透的開獎&對獎的過程。也就是程式會要求使用者輸入6個1~49的相異整數,代表欲對獎的彩券號碼。然後產生6個相異整數,代表某期大樂透開獎的號碼。接著程式會對獎之,並分別輸出開獎號碼、彩券號碼(均小至大排列)及中了幾個號碼!如:
請輸入你的彩券第1個號碼(1~49)
32
請輸入你的彩券第2個號碼(1~49)
4
請輸入你的彩券第3個號碼(1~49)
31
請輸入你的彩券第4個號碼(1~49)
16
請輸入你的彩券第5個號碼(1~49)
28
請輸入你的彩券第6個號碼(1~49)
2
本期開出的號碼(由小至大排列)是:4,7,16,28,33,49
你的彩券的號碼(由小至大排列)是:2,4,16,28,31,32
你中了3個號碼

----------------------------------------------

import java.util.*;
public class BigMoney{
public static final int GUESS = 6;
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int[] input = new int[GUESS];
int[] number = new int[GUESS];
int get = 0;
makeNum(number); //產生樂透號碼

for(int i=0; i<input.length; i++){
System.out.print("請輸入你的彩券第" +i+ "個號碼(1~49):");
input[i] = Integer.parseInt(sc.nextLine()); //將輸入轉成整數存入陣列
for(int j=i; j>0; j--){
if(input[i] == input[j-1] || input[i] > 49){
System.out.println("輸入重複或超出範圍");
i--;
break;
}
}
}

Arrays.sort(number); //陣列做排序
System.out.print("本期開出的號碼(由小至大排列)是:");
for(int i: number) System.out.print(i+ " ");

Arrays.sort(input);
System.out.print("\n你的彩券的號碼(由小至大排列)是:");
for(int i: input){
for(int j: number) if(i == j) get++; //計算有中的號碼
System.out.print(i+ " ");
}
System.out.println("\n你中了" +get+ "個號碼");
}

public static void makeNum(int[] n){
for(int i=0; i<n.length; i++){
n[i] = (int)(Math.random()*49+1);
for(int j=i; j>0; j--){
if(n[i] == n[j-1]){
i--;
break;
}
}
}
}
}

2012年12月2日 星期日

linux防火牆設定

安裝 # yum install system-config-firewall-tui
執行 # system-config-firewall-tui

參考自這裡

2012年12月1日 星期六

CentOS最小安裝之後

照鳥哥的書安裝了CentOS 6之後,發現書上寫的指令對我的linux根本沒作用,對我來說太複雜了。這裡記錄一下簡單一點的設定:

一、先搞上網:
#ifconfig eth0 192.168.1.101 netmask 255.255.255.0
#route add default gw 192.168.1.1
# echo "nameserver 168.95.1.1" > /etc/resolv.conf
最後一項一定要做,不然連不出去;然後鍵盤跟monitor就可以收起來了。

二、在Mac裡用終端機ssh登入:
$ ssh root@192.168.1.101
它會問yes or no?答yes(廢話)
root@192.168.1.101's password: 輸入root的密碼就可以登入了。

三、安裝圖形設定介面並執行
# yum install system-config-network-tui
# system-config-network-tui
把dhcp的星號取消(按空白鍵)


 四、最後設定,剛才的設定開機就不會不見了。
# vi /etc/sysconfig/network-scripts/ifcfg-eth0
把ONBOOT=no改成yes

DEVICE=eth0
HWADDR=00:1a:4d:5a:1c:ff
NM_CONTROLLED=yes
ONBOOT=yes
IPADDR=192.168.1.101
BOOTPROTO=none
NETMASK=255.255.255.0
TYPE=Ethernet
GATEWAY=192.168.1.1
DNS1=168.95.1.1
IPV6INIT=no
USERCTL=no


五、好了。

參考自這裡

2012年11月21日 星期三

SCJP通過了

雖然早已不叫SCJP了,但,管它的!通過了好爽啊,而且還是100%PASS,真是出乎我意料。
我覺得我太幸運了,題目都給的很簡單,我最弱的泛型、IO、指令跟集合(這不是全部了嗎?)幾乎都沒出,太感謝了!(感謝誰?)
考試當中還有個小插曲:當我緊張的做完第一題時,不知道去按到什麼鍵,系統竟然問我是否真的要結束測驗?幹,當時我尿都快出來1cc了,還好沒有手殘去按到Yes,不然我就要在裡面哭29分鐘了…

2012年11月18日 星期日

assert後面的判斷式

assert後面要接判斷式;
若判斷式為true,則沒事;若false,則丟出AssertionError。

*Error不用去處理。

2012年11月10日 星期六

覆寫函式的可控式例外

覆寫規則其中一條是:不能宣告範圍更大或新的exception。
2012.11.18補充:除非新的exception為RuntimeException或其子類別。

例1:

class A{
    A length(){return this;}
}
class Test1 extends A{
        Test1 length()throws NullPointerException{ return this;}

        public static void main(String[] args){
                System.out.println(new Test1().length());
        }
}
------------
Test1@57f0dc

說明:
Test1 length()throws NullPointerException{ return this;}:劃線為合法,因為可宣告回傳型別為父函式的子型別;又因為父函式未宣告exception,所以表示父函式可能丟出任何exception,而NullPointerException為exception的子類別,符合覆寫規則。
證明:
class A{A length()throws NullPointerException{return this;}}
class Test1 extends A{
        Test1 length()throws Exception {return this;}
        public static void main(String[] args){
                System.out.println(new Test1().length());
        }
}
---------------
Test1.java:4: length() in Test1 cannot override length() in A; overridden method does not throw java.lang.Exception
Test1 length()throws Exception {return this;}
              ^

例2:
class MyException extends Exception{}
class A{A length(){return this;}}
class Test1 extends A{
        Test1 length()throws MyException {return this;}
        public static void main(String[] args){
                System.out.println(new Test1().length());
        }
}
----------------
Test1.java:4: length() in Test1 cannot override length() in A; overridden method does not throw MyException
Test1 length()throws MyException {return this;}
              ^
不能丟新的exception。不過明明MyException就有繼承Exception啊,為何還是無法通過編譯呢?

2012.11.18更新
上面觀念錯了,在此重新𨤳淸:
一個覆寫的函式的確不能丟出範圍比父函式要大的例外。
只有一種可以:RuntimeException(包含其子類別)可以由子函式丟出。因為RuntimeException為非可控式例外(unchecked exception)不用去處理;基本上無視它就是了。
所以上面例1的Test1 length()throws NullPointerException{ return this;},NullPointerException為RuntimeException的子類別,所以子函式雖然有宣告,但編譯器無視它,當做沒這回事,當然就能順利編譯。但例2的Test1 length()throws MyException {return this;},MyException為Exception的子類別,非屬於RuntimeException,所以編譯無法通過。

2012年11月6日 星期二

基本資料的型別不同可以比較耶


public class Test1{
        public static void main(String[] args){
                float f = 1f;
                long lo = 1;
                int in = 1;
                double d = 1.0;
                if(f == lo)     System.out.println("1.0==1");
                if(in == d)     System.out.println("1==1.0");
        }
}

------------
1.0==1
1==1.0

應該是做比較的時候會將小型別自動轉型成比較大的那個型別吧。

2012年11月5日 星期一

關於final

1、final類別不能被繼承。
2、final函式不能被覆寫(可繼承)。
3、final變數一定要給初始值,且不能被修改。

2012年11月1日 星期四

關於轉型

轉型是轉參考變數的型別,不是轉物件。

2012年10月29日 星期一

var-args參數

函式的var-args參數宣告要放在後面。

void count(int... x)(){}    //OK!
void count(int x, int... y)(){}    //OK!
void count(int... x, int y)(){}    //NO!!!不能放在前面!

instanceof

if(物件o instanceof 類別A),若物件能通過IS-A類別的測試,回傳true。
所以不管物件o的型別是什麼,看物件就對了。


interface Foo{ }
class Alpha implements Foo{ }
class Beta extends Alpha{ }
public class Delta extends Beta{
        public static void main(String[] args){
                Beta x = new Beta();
                Foo f = (Delta)x;    //這行註解起來可順利執行
                Foo ff = (Alpha)x;
                Beta b = (Beta)(Alpha)x;    //這行能過
        }
}


上面程式碼可順利編譯(因為…我也不知道),但執行只有第7行會出現下面的例外

Exception in thread "main" java.lang.ClassCastException: Beta
at Delta.main(Delta.java:7)

 Beta b = (Beta)(Alpha)x; 
//這行能過是因為x指向的物件是Beta,用instanceof來測試,x is-a Alpha,x is-a Beta,都可以通過IS-A的測試。

Foo f = (Delta)x; 
不能通過的原因是,x is-a Delta,不能通過IS-A測試。

只有try可以嗎?

不可以,會編譯錯誤。有try至少要緊跟著catch或finally其中之一;若兩者都有,finally要跟在catch後面。

try{
    //可能會產生例外的程式碼
}catch(exception e){
    //例外處理
}finally{
    //這裡的程式碼一定會運行
}

length跟length()

String是用length()方法,陣列用length屬性;來返回物件長度。
有點難記…字串方法,陣列屬性嗎?

若參考變數都指向NULL,雖可通過編譯,但執行都會丟出NullPointerException例外。


public class lengthTest{
        public static void main(String[] args){
                String str = null;
                System.out.println(args.length);
                System.out.println(str.length());    //丟出例外
        }
}




0
Exception in thread "main" java.lang.NullPointerException
at lengthTest.main(lengthTest.java:5)

2012年10月28日 星期日

comparTo()

comparTo()為Comparable介面的函式,要實現排序須實作comparTo()函式。
當呼叫Collection.sort()時,系統會依comparTo()的回傳值由小到大做排序。

a, b為物件。
int x = a.comparTo(b);    //由小到大
if a < b, then x < 0
if a = b, then x = 0
if a > b, then x > 0
如果a < b,則x < 0,a.comparTo(b)排序為a b


int x = b.comparTo(a);
if b < a, then x < 0
if b = a, then x = 0
if b > a, then x > 0
如果a < b,則x > 0,b.comparTo(a) 排序為b a

結論:
a.comparTo(b)與b.comparTo(a)的排序結果相反。
記的方法為,a.comparTo(b)就是a - b,若a小減的結果為負,a就放前面;
b.comparTo(a)就是b - a,若a小減的結果為正,a放後面;
兩者剛好相反。



Number抽象類別

The abstract class Number is the superclassof classes BigDecimal, BigInteger, Byte, Short, Integer, Float, Long and Double.
Subclasses of Number must provide methods to convert the represented numeric value to bytedoublefloatintlong, and short.

2012年10月27日 星期六

PriorityQueue的函式

PriorityQueue實作Queue介面,Queue介面繼承Collection介面。
PriorityQueue預設排序為自然排序,或是自定義Comparator。

PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("carrot");
pq.add("apple");
pq.add("banana");       //pq裡元素順序為apple banana carrot
System.out.println(pq.poll()+ ":" +pq.peek());

======
apple:banana


poll():回傳最高優先權元素後予以刪除
peek():回傳最高優先權元素

HashMap宣告

HashMap實作Map介面,Map內為key/value兩個物件的組合,key為唯一值。
HashMap無順序無排序。
因key值為唯一值,必須覆寫equals()判斷物件key,並覆寫hashCode()。

*一旦覆寫equals()同時也必須覆寫hashCode(),因為equals()回傳ture表示兩物件(意義)相同時,因兩物件在記憶體裡位址不同,所以此時hashCode值必定不同,因此必須覆寫hashCode()讓回傳值一致。

HashMap<String, Integer> hmap = new HashMap<String, Integer>();
HashMap<key值, value值>

重要函式有:
put(Object key, Object value)    //將key跟value加入HashMap    ex: hmap.put("abcdef", 1);
keySet()    //以Set回傳key值    ex: Set<String> ss = hmap.keySet();

void addAnimal(List<? extends Animal> animals){}

?為萬用字元,表示任何的意思。
<? extends Animal>的意思是說,任何繼承Animal的子型別。
<? super Animal>的意思是說,任何高於Animal的型別。

?不能用在類別泛型宣告上:
class A<? extends Animal>{ }    //打妹!
class A<Dog extends Animal>{ }    //OK!

取得Iterator的方式

有實作Collection介面就會能取得Iterator:

List<Integer> intList = new ArrayList<Integer>();
Iterator<Integer> ite = intList.iterator();    //返回intList的Iterator

就能用Iterator的函式了:
ite.hasNext();    //看看還有沒有下一個
ite.next();          //丟出後向前跳

HashSet的測試

HashSet實作Set介面,Set介面繼承Collection介面。特性為只有唯一值,而無排序無順序。
未覆寫equals()情況下會測試是否為相同物件後塞入HashSet。

import java.util.*;
public class HashTest{
        String s;
        public HashTest(String s){ this.s = s; }

        public static void main(String[] args){
                HashSet<Object> hs = new HashSet<Object>();
                HashTest ht1 = new HashTest("abcedf");
                HashTest ht2 = new HashTest("abcedf");
                String s1 = new String("abcedf");
                String s2 = new String("abcedf");
                hs.add(ht1);
                hs.add(ht2);
                hs.add(s1);
                hs.add(s2);
                System.out.println(hs.size());
        }
}

==============
3

ht1跟ht2被視為不同物件,而字串s1和s2會被視為相同物件的原因是,String本身就覆寫了equals()的函式。
hs大小為3。

2012年10月26日 星期五

ArrayList的宣告方式

ArrayList:可以動態成長、有快速隨機存取的功能的陣列。

List myList = new ArrayList();    //先寫這樣  
List<String> myList = new ArrayList<String>();  
//再把要加入的物件型別補上,意思就等於String[]

Collection <繼承 List <實作 ArrayList ,Collectionn及List為介面。

equals()和==

equals():值相等
==:指向同一物件


public class EqualsTest{
        public static void main(String[] args){
                String a = "foo";
                String b = "foo";
                String c = new String("foo");
                String d = new String("foo");
                EqualsTest et1 = new EqualsTest();
                EqualsTest et2 = new EqualsTest();

                if(a == b)      System.out.println("Same objects");  //同物件:指向字串常數池的"foo"
                if(a == c)      System.out.println("Same objects");  //不同物件:c的"foo"不在字串池
                else    System.out.println("Different objects");

                if(c == d)      System.out.println("Same objects");  //不同物件
                else    System.out.println("Different objects");

                if(a.equals(b)) System.out.println("Same string");  //回傳true,String有覆寫equals()
                if(a.equals(c)) System.out.println("Same string");  //回傳true,String有覆寫equals()

                if(et1 == et2)  System.out.println("Same objects");  //不同物件
                else    System.out.println("Different objects");

                if(et1.equals(et2))     System.out.println("Same objects");  //不同物件,沒有覆寫equals()

                else    System.out.println("Different objects");


        }
}


==========


Same objects
Different objects
Different objects
Same string
Same string
Different objects
Different objects


2012年10月25日 星期四

參考變數的轉型

class A{}
class B extends A{}
public class CastTest{
        public static void main(String[] args){
                A a = new B();
                B b = (B)new A();    //不能通過IS-A的測試:A IS-A B
                B bb = (B)a;
                a = (A)new B();
        }
}

output:
Exception in thread "main" java.lang.ClassCastException: A
at CastTest.main(CastTest.java:6)

所以可證明物件轉型是看參考變數所指向的物件


==========================

class A{ void showA(){System.out.println("A");} }
class B extends A{ void showB(){System.out.println("B");} }
public class CastTest{
        public static void main(String[] args){
                A a = new B();
                a.showA();
                ((B)a).showB();   //a看不到showB(),必須向下轉型
        }
}

output: 
A
B

method執行看型別,A要執行B的mothed,必須向下轉型成B

覆寫與多載的判斷

覆寫(overriding):
1、基本上要跟原函式一模一樣,包括修飾子、回傳型別及函式名稱,如:
    public void show(){...}
2、可以稍微不一樣的只有修飾子範圍不能小於原修飾子,跟回傳型別可以為原型別的子型別。
3、你不可以覆寫標示為final、static的函式。但可以重新定義標示為static的函式(各自定義)
4、若你不能繼承該函式,你就不能覆寫它。
5、不能宣告原函式沒有宣告的可控式例外。(若父函式沒有宣告可控式例外,則表示它可能丟出任何Exception;所以子函式可宣告任何在Exception內的例外,但不含自定義的例外)

多載(overloading):
1、必須變更參數。(光這項就能抓出一堆偽覆寫函式了)
2、可變更回傳型別。
3、可變更修飾子。
4、可宣告新的或範圍更大的可控式異常。

關於列舉的成員存取

1、enum其實是一個static的類別。
2、在class內的enum就等於是其內部的靜態類別。(inner class)
3、enum內的元素皆為static的String物件。

所以在類別外要存取一個類別內之enum成員,必須當做static類別的static成員來看待:
OuterClass.enumName.enumElement

class Foo{ public enum Direction{ NORTH, SOUTH,  EAST, WEST }}
public class Bar{ Foo.Direction d = Foo.Direction.NORTH; }

2012年10月24日 星期三

javac編譯時選項

-d
指定編譯時class檔存放路徑
javac -d mydir source/MyClass.java    //MyClass.class會存放到mydir目錄裡

-cp 或 -classpath
執行時搜尋class檔的路徑
-cp /dirA:/dirB:.     //以冒號分開不同目錄,句點為目前所在目錄
若編譯時需要用到其他存放在jar檔的class時,需指定class所在目錄或jar檔:
javac -classpath /foo/myLib.jar Book.java

jar檔預設目錄為 $/JAVA_HOME/jre/lib/ext

2012年10月23日 星期二

重要單字

encapsulate     [ɪnˋkæpsə͵let]    封裝

demonstrate    [ˋdɛmən͵stret]    證明;顯示


polymorphism     [͵pɑlɪˋmɔrfɪzm]    多型


suggest    建議


expend    秏盡


effort    [ˋɛfɚt]    盡力


toward    [təˋwɔrd]    朝、向


exhibit    [ɪgˋzɪbɪt]   展示


environment     [ɪnˋvaɪrənmənt]     環境


eligible    [ˋɛlɪdʒəb!]    有資格的


invocation     [͵ɪnvəˋkeʃən]    調用


outcome    [ˋaʊt͵kʌm]     結果


represent    [͵rɛprɪˋzɛnt]    描繪、表現


qualified    [ˋkwɑlə͵faɪd]    合格的、勝任的


indicate    [ˋɪndə͵ket]    指示; 指出


assure    保證


guaranteed    [ˋgærənˋtid]    肯定的


instead     [ɪnˋstɛd]     作為替代


candidate    [ˋkændədet]    候補者[(+for)]


separate    [ˋsɛprɪt]    個別的, 不同的


coupling    [ˋkʌplɪŋ]    耦合    低耦合,即不要跟其它有太多關聨
cohesion    [koˋhiʒən]     內聚     高內聚,功能單一

2012年10月22日 星期一

繼承後的成員變數

class Father{
        int money = 500;
        void spendMoney(int n){
                money -= n;
                System.out.println("Father spend " +n+ ",remain " +money);
        }
}
class Son extends Father{ }

public class Money{
        public static void main(String[] args){
                Father father = new Father();
                Son son = new Son();

                System.out.print("Before father spend money, son has ");
                System.out.println(son.money+ ".");
                father.spendMoney(250);
                System.out.print("After father spend money, son has ");
                System.out.println(son.money+ ".");
        }
}


output:
Before father spend money, son has 500.
Father spend 250,remain 250
After father spend money, son has 500.
自父類別繼承而來的實體變數,會變成自己的實體變數,與父類別無關。

========================================================


class Father{
        int money = 500;
        void spendMoney(int n){ money -= n; }
}
class Son extends Father{
        void spendMoney(int n){
                money -= n;
                super.spendMoney(n);    //這裡呼叫父函式來用,並不是用父物件去呼叫函式
        }
}

public class Money2{
        public static void main(String[] args){
                Father father = new Father();
                Son son = new Son();

                System.out.print("Before son spend money, son has ");
                System.out.println(son.money+ ".");
                son.spendMoney(250);
                System.out.print("After son spend money, son has ");
                System.out.println(son.money+ ".");
                System.out.println("Father has " +father.money);
        }


output:
Before son spend money, son has 500.
After son spend money, son has 0.
Father has 500
呼叫super.spendMoney(n)的意思是,Son物件呼叫父函式(spendMoney())來改變本身value的值,並不是叫Father物件呼叫自已的spendMoney()。因此父物件的value的值並不會變成250。


==================================================



class Father{
        int money = 500;
        void spendMoney(int n){ money -= n; }
}      
class Son extends Father{
        void spendMoney(int n){ super.spendMoney(n); }
        int getMoney(){ return super.money; }
}
           
public class Money2{
        public static void main(String[] args){;
                Son son = new Son();
             
                System.out.print("Before son spend money, he has ");
                System.out.println(son.money+ ".");
                son.spendMoney(250);
                System.out.print("After son spend money, he has ");
                System.out.println(son.getMoney()+ ".");
        }
}

output:

Before son spend money, he has 500.
After son spend money, he has 250.

這裡Son類別內的方法全是存取自Father類別內的方法,仍可正常運作,不會因沒有Father實體而不能存取其實體成員;所以應該可以這樣想:Son類別繼承了Father的field:money、spendMoney(),雖然在Son把spendMoney()給覆寫了,但在呼叫super.spendMoney()時,在編譯器眼裡其實是長這樣:spendMoney(250){ money -=250;}

所以我可以大膽的說,在Son繼承父類別時,在Son裡的spendMoney方法其實有兩個:
void spendMoney(int n){ money -= n; } 跟 void spendMoney(int n){ super.spendMoney(n); }
當呼叫super.spendMoney(n)時,就是呼叫自己的spendMoney(int n){ money -= n; }。
至於為什麼可以這樣想呢?因為啊,就Father類別在程式碼內沒有建立實體啊,所以它的spendMoney()根本不存在啊。Son因為繼承了Father,而且又建立了實體,所以當呼叫super.spendMoney()時,其實就是在跟編譯器說:“嘿,幫我跑一下spendMoney函式,不是跑我覆寫的那一個,是我老爸留給我的那一個spendMoney喔!謝謝!“

====================================================


class Father{
        int money = 500;
        void spendMoney(int n){ money -= n; }
}
class Son extends Father{
        int money = 250;
        void spendMoney(int n){ super.spendMoney(n); }
        void getFathersMoney(Father f){ money = f.money; }
}

public class Money3{
        public static void main(String[] args){;
                Son son = new Son();

                System.out.println("Son has " +son.money+ ".");
                son.getFathersMoney(son);
                System.out.println("Son has " +son.money+ ".");
        }
}



output:

Son has 250.
Son has 500.
這段程式碼是說,兒子偽裝成爸爸去銀行提爸爸的錢。

How to set TAB to 4 spaces in vim?

:set ts=4


標題比內還長…

synchronized


  • 只有函式或區塊可以標上synchronized
    public synchronized void go(){ //code }    //函式
    pubic void go(){ synchronized(this){ //code } }    //區塊
  • 區塊標示法為 synchronized(物件)或synchronized(類別.class)
    synchronized(o)
    synchronized(this)
    synchronized(MyClass.class)

日期格式


  • java.util.Date:
    Date d = new Date();    //建立目前時間的實體
  • java.util.Calender:Calendar為抽象類別,須用靜態函式建立物件
    Calendar c = new Calendar.getInstance();
    c.setTime(d);    //將Date物件指派給c物件
    d = c.getTime();    //將Calendar物件c所設定的時間指派給Date物件d
  • java.util.DateFormat:DateFormat為抽象類別,須用靜態函式建立物件
    DateFormat df = DateFormat.getInstance();
  • java.util.Locale:
    Locale loc = Locale.getDefault();    //取設當地預設格式

2012年10月21日 星期日

關於static


  1. static 函式或變數是屬於類別,被JVM載入時即存在;在物件生成前即存在。
  2. static 函式可透過類別或繼承直接呼叫,或是可用參考變數呼叫:
    class Foo{ static int count = 5; }
    class Abc extends Foo{
        public static void main(String[] args){
            Foo f = new Foo();
            System.out.println(count);
            System.out.println(Foo.count);  
            System.out.println(f.count);    //編譯器是看f的型別(Foo)來呼叫static成員
        }
    }
    //輸出皆為5
  3. static 函式不能存取實體變數或函式(即非static之實體成員)。
  4. static 函式不能被覆寫(overriding)。

函式配對

void go(long n){ System.out.println("long"); }
void go(double n){ System.out.println("double"); }
void go(Integer n){ System.out.println("Integer"); }

int i = 5;
go(5);


output: long

1、函式會依下列參數型別的順序尋找最適合之配對函式:
widening > autoboxing > var-args

2、其中widening(基本資料放寬)會依下列參數型別順序尋找配對:
byte > short > int > long > float > double

3、其中autoboxing(自動包裝成wrapper物件)如下:
boolean --> Boolean
byte --> Byte
short --> Short
char --> Character
int --> Integer
long --> Long
float --> Float
double --> Double

*基本資料可放寬,但wrapper物件不能放寬。Integer無法放寬成Long
void go(Long n){ System.out.println("Long"); }
go(new Integer(5));      //不會放寬

2012年10月17日 星期三

Modifier的可視範圍

private        class

default        class package


protected      class package extends


pubic          any




存取其class成員:
private     同一class裡
default     承上或同一package裡
protected  承上或繼承
public      皆可

2012年10月1日 星期一

toString測試


public class ToStringTest{
public static void main(String[] args){
String x = "big surprise";
int[] y = {1,3};
ToStringTest z = new ToStringTest();

System.out.println(x.toString()+ "\n" +y.toString()+ "\n" +z.toString());
}
}



$ java ToStringTest
big surprise
[I@9b49e6
ToStringTest@10d448



2012年9月29日 星期六

exception測試2

class BadFoodException extends Exception{ }
public class MyException{
    static String[] food = {"Apple", "Banana", "Cocoa", "Coffee", "Toast"};

    public static void main(String[] args){
        try{
            checkFood(args[0]);
        }catch(BadFoodException e){
            System.out.println("I don't like.");
        }
    }
   
    static void checkFood(String input) throws BadFoodException{
        int flag = 0;
        for(String s : food){
            if(s.equals(input)){
                flag = 1;
                break;
            }
        }
        if(flag == 1)    System.out.println("I like it.");
        else throw new BadFoodException();
    }
}



==================================
$ java MyException Toast
I don't like.

$ java MyException Apple
I like it.

2012年9月27日 星期四

exception測試

class Propagate{
    public static void main(String[] args){
        try{
            System.out.println(new Propagate().reverse(""));
        }catch(ArithmeticException e){
            System.out.println("Input error!");
        }finally{
            System.out.println("The main method is done.");
        }
    }
   
    String reverse(String s){
        String reverseStr = "";
       
        if(s.length() == 0)    throw new ArithmeticException();
        else{
            for(int i=s.length()-1; i>=0; --i){
                reverseStr += s.charAt(i);
            }
        }
        return reverseStr;
    }
}



===========
reverse("Hello")
olleH
The main method is done.


reverse("")
Input error!
The main method is done.

例外是隨便挑一個做throw

2012年9月24日 星期一

列舉多載method

public class Bridge{
    public enum Suits{
        CLUBE(20), DIAMONDS(20), HEARTS(30), SPADES(30),
        NOTRUMP(40){
            public int getValue(int bid){
                return (bid - 1) * 30 + 40;
            }
        };
       
        Suits(int points){
            this.points = points;
        }
       
        private int points;
       
        public int getValue(int bid){
            return points * bid;
        }
    }
   
    public static void main(String[] args){
        System.out.println(Suits.NOTRUMP.getValue(3));
        System.out.println(Suits.SPADES + " " + Suits.SPADES.points);
        System.out.println(Suits.values());
    }
}



=========================
100
SPADES 30
[LBridge$Suits;@4a65e0

2012年9月17日 星期一

instanceof測試

class Animal{
    public void testIsA(Animal a){
        System.out.println("Animal");
    }
}
class Dog extends Animal{
    public void testIsA(Animal a){    //a是Animal的參考
        System.out.println(a instanceof Animal);    //但instanceof會看a的物件型別
        System.out.println(a instanceof Dog);
        //a.show();            //此行會產生錯誤,因為a的型別為Animal,而該class無show函式
    }
    public void show(){
        System.out.println("I am class Dog");
    }
}

public class InstanceOfTest{
    public static void main(String[] args){
        Animal dog1 = new Animal();
        Animal dog2 = new Dog();
        Dog dog3 = new Dog();
       
        System.out.println(dog1 instanceof Animal);        //true; Animal IS-A Animal
        System.out.println(dog1 instanceof Dog);        //false; Animal IS-A Dog
        System.out.println(dog2 instanceof Animal);        //true; Dog IS-A Animal
        System.out.println(dog2 instanceof Dog);        //true; Dog IS-A Dog
        System.out.println(dog3 instanceof Animal);        //true; Dog IS-A Dog
       
        dog1.testIsA(dog1);        //Animal,*****
        dog1.testIsA(dog2);        //Animal,overriding取決於呼叫的物件
        dog1.testIsA(dog3);        //Animal,*****
       
        dog1.testIsA(dog1);        //Animal,overriding取決於呼叫的物件
        dog2.testIsA(dog2);        //true, Dog IS-A Animal
                                //true, Dog IS-A Dog
        dog3.testIsA(dog3);        //true,true,
    }
}

======
結論:
1・父類別物件可以呼叫子類別函式(通常父類別看不見子類別內的成員),但只限於被子類別overriding過的函式。
2・不管傳入函式的引數為何,皆以函式之參數的型別宣告為準。
3・而instanceof會去看參考所指向的物件,並以該物件為準。

2012年9月16日 星期日

父類別函式覆寫

 父類別參考指向子類別物件,執行被覆寫之函式

class GameShape{
    public void display(){
        System.out.println("GameShape");
    }
    public void motion(){
        System.out.println("Motion");
    }
}

public class Player1 extends GameShape{
    public void display(){
        System.out.println("Player1");
    }
    public void show(){
        System.out.println("show");
    }
    public void showDad(){
        super.display();
    }
   
    public static void main(String[] args){
        GameShape game = new Player1();
        Player1 player = new Player1();
       
        game.display();
        player.display();
       
        game.motion();
        player.motion();
       
        player.showDad();
        player.show();
    }
}














====================
Player1
Player1
Motion
Motion
GameShape
show

2012年9月11日 星期二

111106_運算式

1.1+2*3+(4+5*6)/(9-7) 2.1*2+3*(4+5)

括號:((1+(2*3))+((4+5*6)/(9-7))) 括號:((1*2)+(3*(4+5)))

前:++1*23/+4*56-97 前:+*12*3+45

後:123*+456*+97-/+ 後:12*345+*+

實作abstract類別

Fruit.java


package food;
public abstract class Fruit{
protected String color;
protected String name;
public void setColor(String str){
color = str;
}
public abstract void show();
}


Apple.java


import food.Fruit;
class Apple extends Fruit{
protected int price;
public Apple(){}
public Apple(int price){
this.price = price;
}
public void setName(String name){
this.name = name;
}
public void setColor(String color){
this.color = color;
}
public void show(){
System.out.println("There is a fruit, it's color is " + color + ",it's an " + name + ".");
System.out.println("And the price of an apple is " + price + ".");
}

public static void main(String[] args){
Apple apple = new Apple(10);
apple.setName("Apple");
apple.setColor("red");
apple.show();
}
}



-------------------------------------------------------------------------

$ java -classpath /Users/superppp/Documents/java Apple

There is a fruit, it's color is red,it's an Apple.
And the price of an apple is 10.



2012年7月6日 星期五

2012年2月8日 星期三

111107_指標變數

當您要取得int變數的記憶體位址時,會使用int*來宣告指標,要取得double變數的記憶體位址時,會使用double*來宣告指標,這是因為它們在進行加減法運算時,所位移的單位並不相同”(出處


原來是這樣啊...難怪我想說指標不是只是一個方向嗎,為什麼還要加上資料型態呢?原來如此,原來如此





我太混啦!

我太混啦!
都過了一年了,說好的一天一個英單呢?