---
# System prepended metadata

title: JAVA(進階程設-期中考前)
tags: [JAVA(進階程設-期中考前)]

---

---
title: JAVA(進階程設-期中考前)
tags: JAVA(進階程設-期中考前)
---

# JAVA程式語言 --- 李鍾斌(進階程設-期中考前)

> 【目次】
> [TOC]
> 
---
# 2019-02-18 class
## 二十一點程式 (一直發牌，每張牌不重複)
* 拿牌 - 比較 - 點數和小於21
* J.Q.K - 10點
* A - 11 or 1
```java=
import java.util.*;
import java.lang.Math;

public class W1 {  
  static int [] poker = new int [52]; //減少資料傳輸(傳遞參數)
  
  public static void main(String[] args) { 
    int point = 0;
    for (int i = 0; i < 52; i++)
      poker[i] = 0;

    int get, now;
    do {
      System.out.println("你目前的點數 = " + point);
      System.out.println("是否要發牌 (1 = yes / 0 = no)？");
      Scanner sc = new Scanner(System.in);
      get = sc.nextInt();
      if ( get == 1 ) {
	      int card = more();
	      now = convert(card);
	      point += now;
      }
    } while(get == 1);
  }
  public static int more(){ //多拿牌
    int card;
    do {
      card = (int)(Math.random()*52);
    } while( poker[card] != 0 );
    poker[card] = 1;
    return(card);
  }
  public static int convert(int card){
    int q, r;
    q = card / 13;
    r = card % 13;
    switch(q){
      case 0:
        System.out.printf("黑桃"); break;
      case 1:
        System.out.printf("紅心"); break;
      case 2:
        System.out.printf("方塊"); break;
      default:
        System.out.printf("梅花");
    }
    switch(r){
      case 10:
        System.out.println("J"); return (10);
      case 11:
        System.out.println("Q"); return (10);  
      case 12:
        System.out.println("K"); return (10);
      case 0:
        System.out.println("A"); return (11);
      default:
        System.out.println(r+1); return (r+1);
    }
  }
}

Output:
你目前的點數 = 0
是否要發牌 (1 = yes / 0 = no)？
1
梅花A
你目前的點數 = 11
是否要發牌 (1 = yes / 0 = no)？
1
方塊Q
你目前的點數 = 21
是否要發牌 (1 = yes / 0 = no)？
1
紅心K
你目前的點數 = 31
是否要發牌 (1 = yes / 0 = no)？
0
```

# 2019-02-25 class

### 21點 --- 點數總和必須小於21點 
* 計算Ace點數 & 判斷是否拿牌 & 點數提醒
```java=
import java.util.*;
import java.lang.Math;

public class W1 {  
  static int [] poker = new int [52]; //減少資料傳輸(傳遞參數)
  
  public static void main(String[] args) { 
    int point = 0;
    for (int i = 0; i < 52; i++)
      poker[i] = 0;

    int get, now;
    do {
          System.out.println("-----------------");
          System.out.println("你目前的點數 = " + point);
          System.out.println("是否要發牌 (1 = yes / 0 = no)？");
          Scanner sc = new Scanner(System.in);
          get = sc.nextInt();
          if (get == 1) {
    	      int card = more();
    	      now = convert(card);
    	      
    	      /* point += now; */
    	      if (now == 11) { //若發到的牌是Ace (A牌當作11點或1點)
    	    	  if (point >= 11) 
                  //若目前點數和已經大於等於11，則Ace算成1點
    	    		  point = point + 1;
    	    	  else  
                  //若目前點數和尚未大於等於11，則Ace算成11點
    	    		  point += now;
    	      } else  //發到的牌不是Ace
    	    	  point += now;
          }
      } while (get == 1 && point < 21);
      
    if (point > 21)
    	System.out.println("點數爆了...");
    else if (point == 21)
	System.out.println("恭喜21點 ~");
    else
	System.out.println("你的總點數和 = " + point);
  }
  public static int more(){ //多拿牌
    int card;
    do {
      card = (int)(Math.random()*52);
    } while( poker[card] != 0 );
    poker[card] = 1;
    return(card);
  }
  public static int convert(int card){
    int q, r;
    q = card / 13;
    r = card % 13;
    switch(q){
      case 0:
        System.out.printf("黑桃"); break;
      case 1:
        System.out.printf("紅心"); break;
      case 2:
        System.out.printf("方塊"); break;
      default:
        System.out.printf("梅花");
    }
    switch(r){
      case 10:
        System.out.println("J"); return (10);
      case 11:
        System.out.println("Q"); return (10);  
      case 12:
        System.out.println("K"); return (10);
      case 0:
        System.out.println("A"); return (11);
      default:
        System.out.println(r+1); return (r+1);
    }
  }
}

Output:
-----------------
你目前的點數 = 0
是否要發牌 (1 = yes / 0 = no)？
1
方塊A
-----------------
你目前的點數 = 11
是否要發牌 (1 = yes / 0 = no)？
1
黑桃A
-----------------
你目前的點數 = 12
是否要發牌 (1 = yes / 0 = no)？
1
方塊9
恭喜21點 ~
```

### 21點：Ace先當作11點，若超出則倒回去將Ace當作1點
* 有考慮之前已發出的牌
```java=
import java.util.*;
import java.lang.Math;

public class W1 {  
  static int [] poker = new int [52]; //減少資料傳輸(傳遞參數)
  
  public static void main(String[] args) { 
    int point = 0;
    for (int i = 0; i < 52; i++)
      poker[i] = 0;

    int get, now;
    int ace11 = 0;
    do {
          System.out.println("-----------------");
          System.out.println("你目前的點數 = " + point);
          System.out.println("是否要發牌 (1 = yes / 0 = no)？");
          Scanner sc = new Scanner(System.in);
          get = sc.nextInt();
          if (get == 1) {
    	      int card = more();
    	      now = convert(card);
    	      
    	      /* point += now; */
    	      if (now == 11) { //若發到的牌是Ace
                  point += 11; //先將ace統一以11點加總
                  ace11++;  //將ace變數內容+1
              } else {  //若發到的牌不是Ace
                  point += now;
              }
              
    	      if (point > 21) { //若加總點數之後已經爆掉
              	if (ace11 > 0){ //則進一步檢查目前加總的點數中是否有以11點計算的ace
              		ace11--;  //如果有，則將ace改為1點計算
              		point -= 10;
              	}
    	      }
          }
      } while (get == 1 && point < 21);
    if (point > 21)
    	System.out.println("點數爆了...");
	else if (point == 21)
		System.out.println("恭喜21點 ~");
	else
		System.out.println("你的總點數和 = " + point);
  }
  public static int more(){ //多拿牌
    int card;
    do {
      card = (int)(Math.random()*52);
    } while( poker[card] != 0 );
    poker[card] = 1;
    return(card);
  }
  public static int convert(int card){
    int q, r;
    q = card / 13;
    r = card % 13;
    switch(q){
      case 0:
        System.out.printf("黑桃"); break;
      case 1:
        System.out.printf("紅心"); break;
      case 2:
        System.out.printf("方塊"); break;
      default:
        System.out.printf("梅花");
    }
    switch(r){
      case 10:
        System.out.println("J"); return (10);
      case 11:
        System.out.println("Q"); return (10);  
      case 12:
        System.out.println("K"); return (10);
      case 0:
        System.out.println("A"); return (11);
      default:
        System.out.println(r+1); return (r+1);
    }
  }
}
    
Output:
-----------------
你目前的點數 = 0
是否要發牌 (1 = yes / 0 = no)？
1
紅心A
-----------------
你目前的點數 = 11
是否要發牌 (1 = yes / 0 = no)？
1
方塊A
-----------------
你目前的點數 = 12
是否要發牌 (1 = yes / 0 = no)？
1
黑桃Q
-----------------
你目前的點數 = 12
是否要發牌 (1 = yes / 0 = no)？
1
方塊J
點數爆了...
```

:::success
### HW01：撲克牌發牌 (21點 --- 加入排序)
1. 以課堂範例改寫，由程式亂數抽取一副牌中的五張，將結果輸出到螢幕。
2. 若能將牌面依點數排序者額外加分。
```java=
import java.util.*;
import java.lang.Math;

public class W1 {  
  static int [] poker = new int [52];
  public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in);
    for (int i = 0; i < 52; i++)
      poker[i] = 0;

    int count = 0, now;
    int now_array [] = new int [5]; //array
    
    while (count < 5) { //抽五張牌
      System.out.printf("---抽第 %d 張牌---\n", count+1 );
      int card = more();
      now = convert(card);
      System.out.println("你目前的點數 = " + now);
      now_array[count] = now;
      count++;
    }
    System.out.printf("=====排序=====\n");     //sort_array
    for (int i = now_array.length - 1; i >= 0; i = i - 1){
    	for (int j = 0; j < i; j = j + 1){
    		if (now_array[j] > now_array[i]){ 	
    			//換（"小於"是由大到小）
    			int tmp = now_array[j];
    			now_array[j] = now_array[i];
    			now_array[i] = tmp;
    		}
    	}
    }
    for (int i = 0; i < now_array.length; i = i + 1)
      System.out.println(now_array[i]);
  }
  
  public static int more(){ //多拿牌
    int card;
    do {
      card = (int)(Math.random()*52);
    } while( poker[card] != 0 );
    poker[card] = 1;
    return(card);
  }
  public static int convert(int card){
    int q, r;
    q = card / 13;
    r = card % 13;
    switch(q){
      case 0:
        System.out.printf("黑桃"); break;
      case 1:
        System.out.printf("紅心"); break;
      case 2:
        System.out.printf("方塊"); break;
      default:
        System.out.printf("梅花");
    }
    switch(r){
      case 10:
        System.out.println("J"); return (10);
      case 11:
        System.out.println("Q"); return (10);  
      case 12:
        System.out.println("K"); return (10);
      case 0:
        System.out.println("A"); return (11);
      default:
        System.out.println(r+1); return (r+1);
    }
  }
}

Output:
---抽第 1 張牌---
紅心A
你目前的點數 = 11
---抽第 2 張牌---
梅花9
你目前的點數 = 9
---抽第 3 張牌---
梅花8
你目前的點數 = 8
---抽第 4 張牌---
方塊2
你目前的點數 = 2
---抽第 5 張牌---
方塊J
你目前的點數 = 10
=====排序=====
2
8
9
10
11
```
:::

# 2019-03-04 class
## 二十一點程式 (花色、點數、排序)
```java=
import java.util.*;
import java.lang.Math;
  
public class W1 {
  static int [] poker = new int [52];
  static int [] p = new int[5]; //用來記錄手上五張牌的點數
  static int [] f = new int[5]; //用來記錄手上五張牌的花色
  
  public static void main(String[] args) { 
    for (int i = 0; i < 52; i++)
      poker[i] = 0;
    Scanner sc = new Scanner(System.in);

    int get, now;
    System.out.println("### 排序前 ###");
    for (int i = 0; i < 5; i++){
      int card = more();
      System.out.println("-----"+card); 
      //除錯用。將亂數列印出來。
      now = convert(card);
      p[i] = card % 13; //餘數-點數
      f[i] = card / 13; //商-花色
      System.out.printf("花色：%d\t點數：%d\n", f[i], p[i]);
    }
    sort(f,p);
    System.out.println("### 排序後 ###");
    for (int i = 0; i < 5; i++)
      System.out.printf("%d\t%d\n", f[i], p[i]);
  }
  public static void sort(int [] f, int [] p){
    int t; //用來暫存排序中的資料
    for (int i = 0; i < 5; i++)
      for (int j = 0; j < 5; j++)
      if (p[i] > p[j]){ //若第i張牌點數大於第j張牌
        t = p[i]; //將點數陣列中兩張牌的位置互換
        p[i] = p[j];
        p[j] = t;
        t = f[i]; //將花色陣列中兩張牌的位置互換
        f[i] = f[j];
        f[j] = t;
    }
  }
  public static int more(){ //多拿牌
    int card;
    do {
      card = (int)(Math.random()*52);
    } while( poker[card] != 0 );
    poker[card] = 1;
    return(card);
  }
  public static int convert(int card){
    int q,r;
    q = card / 13;
    r = card % 13;
    switch(q){
	    case 0:
	    	System.out.printf("黑桃"); break;
	    case 1:
	    	System.out.printf("紅心"); break;
	    case 2:
	    	System.out.printf("方塊"); break;
	    default:
	    	System.out.printf("梅花");
    }
    switch(r){
    	case 10:
    		System.out.println("J"); return (11);
    	case 11:
    		System.out.println("Q"); return (12);
    	case 12:
    		System.out.println("K"); return (13);
    	case 0:
    		System.out.println("A"); return (1);
    	default:
    		System.out.println(r+1); return (r+1);
    }
  } 
}

Output:
### 排序前 ###
-----26
方塊A
花色：2	點數：0
-----12
黑桃K
花色：0	點數：12
-----50
梅花Q
花色：3	點數：11
-----18
紅心6
花色：1	點數：5
-----2
黑桃3
花色：0	點數：2
### 排序後 ###
0	12
3	11
1	5
0	2
2	0
```
:::success
### HW02：撲克牌五種牌型判斷
* 程式要能正確判斷同花，順子，大順，同花順，以及同花大順
```java=
import java.util.*;
import java.lang.Math;
  
public class W1 {
  static int [] poker = new int [52];
  static int [] p = new int[5]; 
  //用來記錄手上五張牌的點數
  static int [] f = new int[5]; 
  //用來記錄手上五張牌的花色
    
  //static int [] p = {0,9,10,11,12}; 
  //static int [] f = {0,0,0,0,0}; 
    
  public static void main(String[] args) { 
    for (int i = 0; i < 52; i++)
      poker[i] = 0;
    Scanner sc = new Scanner(System.in);
    
    int get, now;
    System.out.println("### 排序前 ###");
    for (int i = 0; i < 5; i++){
      int card = more();
      System.out.println("-----"+card); //除錯用。將亂數列印出來。
      now = convert(card);
      p[i] = card % 13; //餘數-點數
      f[i] = card / 13; //商-花色
      System.out.printf("%d\t%d\n", f[i], p[i]);
    }
    sort(f,p);
    System.out.println("### 排序後 ###");
    for (int i = 0; i < 5; i++)
      System.out.printf("%d\t%d\n", f[i], p[i]);
    
    //順子、大順、同花、同花順、同花大順
    if ( p[0]-p[1] == 1 && p[1]-p[2] == 1 &&
         p[2]-p[3] == 1 && p[3]-p[4] == 1 )
      System.out.println("順子");
    if ( p[0] == 12 && p[1] == 11 && p[2] == 10 && 
         p[3] == 9 && p[4] == 0 )
      System.out.println("大順");
    if ( f[0]==f[1] && f[1]==f[2] && 
         f[2]==f[3] && f[3]==f[4] )
      System.out.println("同花");
    if ((p[0]-p[1] == 1 && p[1]-p[2] == 1 && 
         p[2]-p[3] == 1 && p[3]-p[4] == 1) && (f[0]==f[1] 
         && f[1]==f[2] && f[2]==f[3] && f[3]==f[4]))
      System.out.println("同花順");
    if ((p[0] == 12 && p[1] == 11 && p[2] == 10 && 
         p[3] == 9 && p[4] == 0 ) && (f[0]==f[1] 
         && f[1]==f[2] && f[2]==f[3] && f[3]==f[4]))
      System.out.println("同花大順");
  }
  public static void sort(int [] f, int [] p){
    int t; //用來暫存排序中的資料
    for (int i = 0; i < 5; i++)
      for (int j = 0; j < 5; j++)
        if (p[i] > p[j]){ //若第i張牌點數大於第j張牌
          t = p[i]; //將點數陣列中兩張牌的位置互換
          p[i] = p[j];
          p[j] = t;
          t = f[i]; //將花色陣列中兩張牌的位置互換
          f[i] = f[j];
          f[j] = t;
        }
  }
  public static int more(){ //多拿牌
    int card;
    do {
      card = (int)(Math.random()*52);
    } while( poker[card] != 0 );
    poker[card] = 1;
    return(card);
  }
  public static int convert(int card){
    int q,r;
    q = card / 13;
    r = card % 13;
    switch(q){
	    case 0:
	    	System.out.printf("黑桃"); break;
	    case 1:
	    	System.out.printf("紅心"); break;
	    case 2:
	    	System.out.printf("方塊"); break;
	    default:
	    	System.out.printf("梅花");
    }
    switch(r){
    	case 10:
    		System.out.println("J"); return (11);
    	case 11:
    		System.out.println("Q"); return (12);
    	case 12:
    		System.out.println("K"); return (13);
    	case 0:
    		System.out.println("A"); return (1);
    	default:
    		System.out.println(r+1); return (r+1);
    }
  } 
}

Output:
### 排序前 ###
-----0
黑桃A
0	0
-----12
黑桃K
0	12
-----24
紅心Q
1	11
-----36
方塊J
2	10
-----35
方塊10
2	9
### 排序後 ###
0	12
1	11
2	10
2	9
0	0
大順
```
---
### HW02b：撲克牌十種牌型判斷
* 除了HW02的五種牌型，另外要能判斷一對(aabcd, abbcd,abccd,abcdd)，兩對(aabbc,abbcc,aabcc)，三條，鐵支，葫蘆
* 總共有幾種不同點數：m，最多同點數的張數：n
* 一對(m=4,n=2)、二對(m=3,n=2)、三條(m=3,n=3)、葫蘆(m=2,n=3)、鐵支(m=2,n=4)
```java=
import java.lang.Math;

public class W1 {
	static int [] poker = new int [52];
	static int [] po = new int[5]; //用來記錄手上五張牌的點數
	static int [] fl = new int[5]; //用來記錄手上五張牌的花色
	
	public static void main(String[] args) { 
    int card_num = 0; //第幾張牌，最多5張牌
    int get_point, f, p, i, j;
    for(i = 0; i < 52; i++) //陣列歸零，表示52張牌尚未被取
    	poker[i] = 0;
    do{
    	get_point = (int)(Math.random()*52);
    	//若亂數儲存格為0,表示未抽到
        if(poker[get_point] == 0){ 
            //將該儲存格表為1
            poker[get_point] = 1;		
            f = get_point / 13; p = get_point % 13;
                //將花色和點數分別記錄在對應位置
            fl[card_num] = f; po[card_num] = p;	
            //成功抽出的牌數為+1
            card_num++;		
                //呼叫牌面花色點數轉換之函式
            transform(f, p);	
            System.out.printf("\t");
    	}
    } while(card_num < 5);//成功抽出之牌數=5離開
    System.out.println();
    for(i = 0; i < 5; i++) {
    	System.out.printf("f[%d] = %d, p[%d] = %d\n", 
                            i, fl[i], i, po[i]);
    }
    for(i = 0; i < 5; i++)
        for(j = i + 1; j < 5; j++)
            if(po[i] > po[j]){	//大的放後面
                int temp;
                temp = po[i]; po[i] = po[j]; po[j] = temp;
                temp = fl[i]; fl[i] = fl[j]; fl[j] = temp;
            }
    	for(i = 0; i < 5; i++)
    		System.out.printf("f[%d]=%d,p[%d]=%d\n",
                                    i,fl[i],i,po[i]);
    	if(straight(po))
    		System.out.println("順子");
    	else if(fullhouse(po, fl))
    		System.out.println("葫蘆");
    	else if(iron(po))
    		System.out.println("鐵支");
    	else if(three(po))
    		System.out.println("三條");
    	else if(twopair(po))
    		System.out.println("二對");
    	else if(onepair(po))
    		System.out.println("一對");
	}
	public static Boolean straight(int [] p){
        // 幾種點數=a 最多同點數張數=b
            int card_num = 1; 
            for(int i = 0; i < 4; i++){
                if(p[i] + 1 == p[i+1])
                    card_num *= 1;
                else
                    card_num *= 0;
            }
            if(card_num == 1)
                return(true);
            else
                return(false);
	}
	public static Boolean onepair(int [] p){
	// 幾種點數=a 最多同點數張數=b
            int card_num = 0; 
            for(int i = 0; i < 4; i++){
                if(p[i] == p[i+1])
                    card_num += 1;
                else
                    card_num += 0;
            }
            if(card_num == 1)
                return(true);
            else
                return(false);
        }
	public static Boolean twopair(int [] p){
	// 幾種點數=a 最多同點數張數=b
            int card_num = 0; 
            for(int i = 0; i < 4; i++){
                if(p[i] == p[i+1])
                    card_num += 1;
                else
                    card_num += 0;
            }
            if(card_num == 2)
                return(true);
            else
                return(false);
        }
	public static Boolean three(int [] p){
        // 幾種點數=a 最多同點數張數=b
            int card_num = 0; 
            for(int i = 0; i < 3; i++){
                if(p[i] == p[i+1] && p[i] == p[i+2])
                    card_num += 1;
                else
                    card_num += 0;
            }
            if(card_num == 1)
                return(true);
            else
                return(false);
        }
	public static Boolean iron(int [] p){
        // 幾種點數=a 最多同點數張數=b
            int card_num = 0; 
            for(int i = 0; i < 2; i++){
                if( p[i] == p[i+1] && p[i] == p[i+2] 
                    && p[i] == p[i+3])
                    card_num += 1;
                else
                    card_num += 0;
            }
            if(card_num == 1)
                return(true);
            else
                return(false);
            }
	public static Boolean fullhouse(int [] p,int [] f){
		if(p[0]==p[1] && p[0]==p[2] && p[3]==p[4] || 
                  p[0]==p[1] && p[2]==p[3]&&p[2]==p[4])
			return(true);
		else
			return(false);
	}
    public static void transform(int j, int k){
    	switch(j){
	        case 0:
	        	System.out.printf("黑桃"); break;
	        case 1:
	        	System.out.printf("紅心"); break;
	        case 2:
	        	System.out.printf("方塊"); break;
	        default:
	        	System.out.printf("梅花");
    	}
    	if(k==0)
    		System.out.printf("A");
    	else if(k==10)
    		System.out.printf("J");
    	else if(k==11)
    		System.out.printf("Q");
    	else if(k==12)
    		System.out.printf("K");
    	else
    		System.out.print(k + 1);//這不能用f
    }
}

Output:
方塊6	黑桃5	方塊3	紅心7	梅花4	
f[0] = 2, p[0] = 5
f[1] = 0, p[1] = 4
f[2] = 2, p[2] = 2
f[3] = 1, p[3] = 6
f[4] = 3, p[4] = 3
f[0]=2,p[0]=2
f[1]=3,p[1]=3
f[2]=0,p[2]=4
f[3]=2,p[3]=5
f[4]=1,p[4]=6
順子
```
:::

# 2019-03-11 class 
## ***Java 物件導向***
* 類似`import java.util.*;`，可從外面引入或呼叫的作用。(組裝)
* 優點：`副程式(Proj 1, Proj 2, Proj 3)`可以被不同的`主程式`重複使用。
![](https://i.imgur.com/bRIRERe.png)

```java=
### 原始版：變數宣告在主程式裡 ###

import java.util.*;

public class Week04 {
  public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in);
    System.out.println("請輸入矩形的長：");
    int length = sc.nextInt();
    System.out.println("請輸入矩形的寬：");
    int width = sc.nextInt();
    int area = compute(length, width);
    System.out.println("面積 = " + area);
  }
  public static int compute(int l, int w){
    return (l*w);
  }
}

Output:
請輸入矩形的長：
3
請輸入矩形的寬：
2
面積 = 6
```
* 物件導向的寫法：
  1. New Java Class：Square
  2. Include main method：不打勾
```java=
### 主程式 Week04.java ###

import java.util.*;

public class Week04 {
  public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in);
    Square sq = new Square();
    
    System.out.println("請輸入矩形的長：");
    sq.length = sc.nextInt();              
    // int length = sc.nextInt();
    
    System.out.println("請輸入矩形的寬：");
    sq.width = sc.nextInt();               
    // int width = sc.nextInt();
    
    System.out.println("面積 = " + sq.compute_area());   
    // int area = compute(length, width);
  }
}

### 副程式 Square.java ###

public class Square {
    int length; //這個類別程式中的資料成員(變數)
    int width;
    public int compute_area(){ //用來計算矩形面積的方法成員(函式)
      return(length * width);
    }
}
```
* 西洋棋士兵

```java=
### 主程式 Week04.java ###

import java.util.*;

public class Week04 {
  public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in);
    Soldier s1 = new Soldier();
    s1.x = 2; s1.y = 2; //將士兵s1的起始座標設在(2,2)
    s1.move(0);
    
    Soldier s2 = new Soldier();
    s2.x = 4; s2.y = 2; //將士兵s2的起始座標設在(4,2)
    s2.take(1);
    
    System.out.printf("s1士兵的位置在(%d,%d)\n", s1.x, s1.y);
    System.out.printf("s2士兵的位置在(%d,%d)\n", s2.x, s2.y);
  }
}

### 副程式 Soldier.java ###
public class Soldier {
  int x, y; //紀錄棋子的座標
  int owner; //用來記錄棋子是哪一個玩家的(上：0/下：1)
  public void move(int d){
    switch(d){
      case 0: //往上走
        y++; break;
      case 2: //往右走
        x++; break;
      case 4: //往下走
        y--; break;
      case 6: //往左走
        x--; break;
      default:
        System.out.println("方向錯誤！！");
    }
  }
  public void take(int d){ 
    //呼叫此動作需檢查玩家身分是否有子可吃，以及改變士兵位置
    x++;
    y--;
  }
}

Output:
s1士兵的位置在(2,3)
s2士兵的位置在(5,1)
```

:::success
### HW03：物件導向練習-西洋棋士兵
* 模擬士兵棋子吃的動作，撰寫必要程式碼檢查相對位置是否有子可吃，以及吃完後座標的改變
```java=
### 主程式 KK.java ###

import java.util.*;
public class KK {
  public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in);
    Knight kk = new Knight();
    kk.set_position(0,0);
    kk.show_position();
    while(true){
      System.out.println("請輸入騎士的移動方向(1-8):");
      kk.move(sc.nextInt());
      kk.show_position();
    }
  }
}

### 副程式 Knight.java ###

public class Knight {
  int x,y;
  public void set_position(int a, int b){
    x=a; y=b; 
  }
  public void show_position(){
    System.out.printf("騎士所在位置=(%d,%d)\n",x,y);
  }
  public void move(int i){ //我們輸入的數字
    if(i==1){ x++; y += 2; }
    if(i==2){ x += 2; y++; }
    if(i==3){ x += 2; y--; }
    if(i==4){ x++; y -= 2; }
    if(i==5){ x--; y -= 2; }
    if(i==6){ x -= 2; y--; }
    if(i==7){ x -= 2; y++; }
    if(i==8){ x--; y += 2; }
  }  
}

Output:
騎士所在位置=(0,0)
請輸入騎士的移動方向(1-8):
2
騎士所在位置=(2,1)
請輸入騎士的移動方向(1-8):
5
騎士所在位置=(1,-1)
請輸入騎士的移動方向(1-8):
```
:::
---
# 2019-03-18 class 
## 物件導向 (簡單輸出)
```java=
# Week05.java #

public class Week05 {
  public static void main(String[] args) { 
    Student st = new Student();
    st.id = 87654321;
    st.sex = true;
    st.grade = 2;
    System.out.println(st.id);
  }
}

# Student.java #

public class Student {
  //定義屬性
  int id; 
  boolean sex; 
  int grade;
}

Output:
> run Week05
87654321
```
## 物件導向 (透過呼叫函式輸出)
```java=
# Week05.java #

public class Week05 {
  public static void main(String[] args) { 
    Student st = new Student();
    st.id = 87654321;
    st.sex = true;
    st.grade = 2;
    
    st.x = 0; st.y = 2;
    st.showposition();
  }
}

# Student.java #

public class Student {
  //定義屬性
  int id; 
  boolean sex; 
  int grade;
  int x, y; //目前座標
  public void showposition(){
    System.out.printf("目前所在位置為(%d,%d)\n", x, y);
  }
}

Output:
> run Week05
目前所在位置為(0,2)
```
## 物件導向 (呼叫函式，輸出註冊狀態)
```java=
# Week05.java #

public class Week05 {
  public static void main(String[] args) { 
    Student st = new Student();
    
    st.register = 1;
    st.showregister(st.register);
  }
}

# Student.java #

public class Student {
  int register; //目前註冊狀態 0=休學 1=正常 2=待確定

  public int showregister(int register){
    switch(register){
      case 0:
        System.out.println("休學");
        return (11);
      case 1:
        System.out.println("正常");
        return (12);
      case 2:
        System.out.println("待確定");
        return (13);
      default:
        System.out.println("---");
        return (register);
    }
  }
}

Output:
> run Week05
正常
```

## 物件導向-計算面積
* 多載 (overloading)
    * 函式名稱相同，但參數個數不同 => 可成功執行
```java=
# Week5_computer.java #

public class Week5_computer {
  public static void main(String[] args) { 
    Computer c = new Computer();
    System.out.println("矩形面積 = " + c.rectangle_area(5, 3));
    System.out.println("正方形面積 = " + c.rectangle_area(5));
    System.out.println("矩形面積 = " + c.rectangle_area(5.3));
  }
}

# Computer.java #

public class Computer {
  public int rectangle_area(int a, int b){
    return (a*b);
  }
  public int rectangle_area(int a){
    return (a*a);
  }
  public double rectangle_area(double a){
    return (a*a);
  }
}

Output:
> run Week5_computer
矩形面積 = 15
正方形面積 = 25
矩形面積 = 28.09
```

* 計算圓面積
```java=
# Week5_circle.java #

public class Week5_circle {
  public static void main(String[] args) { 
    Circle c = new Circle();
    System.out.println("圓形面積 = " + c.circle_area(3));
    System.out.println("圓形面積 = " + c.circle_area(5.3));
  }
}

# Circle.java #

public class Circle {
  double pi = 3.14;
  public double circle_area(double a){
    return (a*a*pi);
  } 
}

Output:
圓形面積 = 28.26
圓形面積 = 88.2026
```
## 物件導向 - static概念
* `static`：靜態的。
* 若==宣告`static`==，在電腦裡永遠只有一份。不管有幾個實體，大家都==共用一份==。
* 若==沒有宣告`static`==，在電腦裡可以有很多份。有多個不同的實體，大家的==值都不同==。

```java=
public class Week05 {
  public static void main(String[] args) { 
    Week05 w5 = new Week05();
    w5.hola();   //實體成員
    hello();     //類別成員
  }
  public void hola(){                 //實體
    System.out.println("Hola!!!");
  }
  public static void hello(){         //類別：不屬於任何物件(實體)
    System.out.println("Hello!!");
  }
}

Output:
> run Week05
Hola!!!
Hello!!
```

## 物件導向 - 建構式(constructor)
* 當有建構式時，java先執行。
* `建構式`內，可以放預設值。
```java=
# Week05.java #

public class Week05 {
  public static void main(String[] args) { 
    Student st = new Student();
    System.out.println(st.name);
  }
}

# Student.java #

public class Student {
  String name = "John Doe";
  int x, y; //目前座標

  public Student(){ //建構式
    name = "Lebron Default";
  }
  public void showposition(){
    System.out.printf("目前所在位置為(%d,%d)\n", x, y);
  }
}

Output:
> run Week05
Lebron Default
```

### 建構式 (constructor) + 多載 (overloading)
```java=
# Week05.java #

public class Week05 {
  public static void main(String[] args) { 
    Student s1 = new Student();
    System.out.println(s1.name);
    
    Student s2 = new Student("Stefen Curry");
    System.out.println("第二號學生的姓名：" + s2.name);
  }
}

# Student.java #

public class Student {
  String name = "John Doe";
  
  public Student(){ //建構式
    name = "Lebron Default";
  }
  public Student(String s){ //利用多載觀念的引數建構式
    name = s;
  }
}

Output:
> run Week05
Lebron Default
第二號學生的姓名：Stefen Curry
```
:::success
### HW04：OOP建構式與多載範例 (點名)
:::
---

# 2019-03-25 class
```flow
op=>operation: Chess (父)
op2=>operation: Knight (子)
op->op2
```
## 基本的建構式
```java=
# Test1.java #

public class Test1 {
  public static void main(String[] args) { 
    Test_Chess1 cc = new Test_Chess1();
    cc.show_position();
  }
}

# Test_Chess1.java #

public class Test_Chess1 {  
  int x, y; //記錄西洋棋子的座標位置
  boolean player; //區分棋子是哪一個玩家的
  public Test_Chess1() {
    System.out.println("執行Chess類別的建構式");
    x = 0; y = 0;
  }
  public void show_position(){
    System.out.printf("棋子在(%d,%d)\n", x, y);
  }
}

Output:
> run Test1
執行Chess類別的建構式
棋子在(0,0)
```
## 有/無引數建構式
```java=
# Week06.java #

public class Week06 {
  public static void main(String[] args) { 
    Chess cc = new Chess();
    cc.show_position();
    
    Chess c2 = new Chess(5,3);
    c2.show_position();
  }
}

# Chess.java #

public class Chess {  
  int x, y; //記錄西洋棋子的座標位置
  boolean player; //區分棋子是哪一個玩家的
  public Chess() {
    System.out.println("執行Chess類別的無引數建構式");
    x = 0; y = 0;
  }
  public Chess(int a, int b){
    System.out.println("執行Chess類別的有引數建構式");
    x = a; y = b;
  }
  public void show_position(){
    System.out.printf("棋子在(%d,%d)\n", x, y);
  }
}

Output:
> run Week06
執行Chess類別的無引數建構式
棋子在(0,0)
執行Chess類別的有引數建構式
棋子在(5,3)
```
## 物件導向 (繼承) & 有/無覆蓋
```java=
# Week06.java #

public class Week06 {
  public static void main(String[] args) { 
    /*
     * Chess cc = new Chess();
    cc.show_position();
    
    Chess c2 = new Chess(5,3);
    c2.show_position();
    */
    Knight kk = new Knight();
    kk.show_position();
    
    Soldier ss = new Soldier();
    ss.show_position();
  }
}

# Chess.java #

public class Chess {  
  int x, y; //記錄西洋棋子的座標位置
  boolean player; //區分棋子是哪一個玩家的
  public Chess() {
    System.out.println("執行Chess類別的無引數建構式");
    x = 0; y = 0;
  }
  public Chess(int a, int b){
    System.out.println("執行Chess類別的有引數建構式");
    x = a; y = b;
  }
  public void show_position(){
    System.out.printf("棋子在(%d,%d)\n", x, y);
  }
}


# Knight.java #

public class Knight extends Chess { //裡面完全沒有定義，只有繼承 Chess
  /*
  public void move(){
  }
  */
}

# Soldier.java #

public class Soldier extends Chess {
  int x, y; //用來記錄士兵在棋盤座標的變數
  boolean player; //用來區分棋子是哪一個玩家的
  public Soldier(){
    x = 0; y = 0;
  }
  public void show_position(){
    System.out.printf("士兵在(%d,%d)\n", x, y); //覆蓋掉繼承的東西了
  }
  public void move(int i){
  }
}

Output:
> run Week06
執行Chess類別的無引數建構式
棋子在(0,0)
執行Chess類別的無引數建構式
士兵在(0,0)
```
---
## 二維
```java=
# W6.java #

public class W6 {
  public static void main(String[] args) { 
    Coordinate2D m2 = new Coordinate2D();
    m2.whereami();
  }
}

# Coordinate2D.java #

public class Coordinate2D {
  int x = 5; int y = 5;
  public void whereami(){
    System.out.printf("(%d,%d)\n",x,y);
  }
}

Output:
> run W6
(5,5)
```

## 三維 繼承 二維
```java=
# W6.java #

public class W6 {
  public static void main(String[] args) { 
    Coordinate2D m2 = new Coordinate2D();
    m2.whereami();
    
    Coordinate3D m3 = new Coordinate3D();
    m3.whereami();
  }
}

# Coordinate2D.java #

public class Coordinate2D {
  int x = 5; int y = 5;
  public void whereami(){
    System.out.printf("(%d,%d)\n",x,y);
  }
}

# Coordinate3D.java #

public class Coordinate3D extends Coordinate2D{
  int z = 9;
  public void whereami(){
    System.out.printf("(%d,%d,%d)\n",x,y,z);
  }
}

Output:
> run W6
(5,5)
(5,5,9)
```
:::success
### HW05：OOP練習-繼承
![](https://i.imgur.com/nUb6WqL.png)
* 根據課堂白板上的要求，製作各種交通工具的類別，再設計自我介紹的函式輸出其特徵

* Vehicle
```java=
public class Vehicle {
    String power = "未知"; 	// 動力來源
    int passenger = 0; 	//搭載人數
    int wheel = 0; 		//輪胎數

    public static void main(String[] args) { 
        Vehicle v = new Vehicle();      
        v.selfie();

        Suv ss = new Suv(); 			
        ss.selfie();
        Coupe cc = new Coupe(); 		
        cc.selfie();
        Motorbike mm = new Motorbike(); 
        mm.selfie();
        Bicycle bb = new Bicycle(); 	
        bb.selfie();

        String power = "人力"; 
        int passenger = 2; 
        int wheel = 3;
        Tricycle tt = new Tricycle();	
        tt.selfie(power, passenger, wheel);
    }
    public Vehicle() {
        power = "汽油/電力";
        passenger = 0;
        wheel = 0;
        /* System.out.printf("Vehicle 動力來源：%s\t 
         * 搭載人數：%d\t 輪胎數：%d\n",
         * power, passenger, wheel); */
    }
    public void selfie(){
        System.out.printf("Hello! 我是交通工具~\n");
        System.out.printf(
        "Vehicle 動力來源：%s\t搭載人數：%d \t輪胎數：%d\n", 
        power, passenger, wheel);
    }
}
```
* Car
```java=
public class Car extends Vehicle {
  public Car() {
    System.out.println("======= Car =======");
    passenger = 4;  wheel = 4; power = "汽油/電力";
    System.out.printf(
    "Car 動力來源：%s\t 搭載人數：%d\t輪胎數：%d\n", 
    power, passenger, wheel);
  }
  public void selfie(){
    System.out.printf("我是car\n");
  }
}
```
* Suv
```java=
public class Suv extends Car {
    public void selfie(){
        passenger = 6;  wheel = 4; power = "汽油/電力";
        System.out.printf(
        "Suv 動力來源：%s\t 搭載人數：%d\t輪胎數：%d\n", 
        power, passenger, wheel);
        System.out.printf("Suv：休旅車\n");
    }
}
```
* Coupe
```java=
public class Coupe extends Car{
  public void selfie(){
    System.out.printf("Coupe：雙門轎跑車\n");
  }
}
```
* Motorbike
```java=
public class Motorbike extends Vehicle {
    public Motorbike() {
        //String power;
        System.out.printf("======= Motorbike =======\n");
        passenger = 2;  wheel = 2; power = "電力";
        System.out.printf(
        "Motorbike 動力來源：%s\t搭載人數：%d \t輪胎數：%d\n", 
        power, passenger, wheel);
    }
    public void selfie(){
        System.out.printf("我是 Motorbike\n");
    }
}
```
* Bike
```java=
public class Bike extends Vehicle {
  public Bike() {
    System.out.printf("======= Bike =======\n");
    passenger = 1;  wheel = 2; power = "人力";
    System.out.printf("Bike動力來源：%s\n", power);
    System.out.printf("Bike搭載人數：%d\n", passenger);
    System.out.printf("Bike輪胎數：%d\n", wheel);
  }
  public void selfie(){
    System.out.printf("我是 Bike\n");
  }
}
```
* Bicycle
```java=
public class Bicycle extends Bike{
  public void selfie(){
    System.out.printf("Bicycle：腳踏車\n"); 
  }
}
```

* Tricycle
```java=
public class Tricycle { /* extends Bike */
    String power;
    int passenger;
    int wheel;
    public void selfie(String pow, int pas, int w){
        System.out.println("======= Bike: Tricycle =======");
        System.out.printf(
        "Tricycle 動力來源：%s\t搭載人數：%d \t輪胎數：%d\n",
        pow, pas, w);
        System.out.printf("Tricycle：三輪車\n"); 
        //覆蓋掉繼承的東西了
    }
}
```
```
Hello! 我是交通工具~
Vehicle 動力來源：汽油/電力	搭載人數：0 	輪胎數：0
======= Car =======
Car 動力來源：汽油/電力	 搭載人數：4	輪胎數：4
Suv 動力來源：汽油/電力	 搭載人數：6	輪胎數：4
Suv：休旅車
======= Car =======
Car 動力來源：汽油/電力	 搭載人數：4	輪胎數：4
Coupe：雙門轎跑車
======= Motorbike =======
Motorbike 動力來源：電力	搭載人數：2 	輪胎數：2
我是 Motorbike
======= Bike =======
Bike動力來源：人力
Bike搭載人數：1
Bike輪胎數：2
Bicycle：腳踏車
======= Bike: Tricycle =======
Tricycle 動力來源：人力	搭載人數：2 	輪胎數：3
Tricycle：三輪車
```
:::
---
# 2019-04-08 class
> [What is private, public and protected in Java?](https://www.quora.com/What-is-private-public-and-protected-in-Java)

1. public：表明該數據成員、成員函數是對所有用戶開放，所有用戶都可以直接進行調用。
    * (任何人都可以用)
3. protected：對於子女、朋友來说，就是public的，可以自由使用，没有任何限制。而對於其他的外部class，protected就變成private。
    * (允許存取其他資料夾的權限)
5. private：表示私有，就是除了class自己之外，任何人都不可以直接使用，即便是子女，朋友，都不可以使用。 


## 讀取外部`name.txt`的內容
```java=
import java.io.*;

public class Week08 {
  public static void main(String[] args) { 
    /* 例外處理 */
    
    try {
      FileReader fr = new FileReader("name.txt");
      BufferedReader br = new BufferedReader(fr); //緩衝區
      String line;
      while ((line = br.readLine()) != null) {
        System.out.println(line);
      }
    }
    catch (IOException e){System.out.println(e);}
  }
}
```

## 匯出檔案`out.txt`
```java=
import java.io.*;

public class Week08b {
  public static void main(String[] args) { 
    try { /* 例外處理 */
      FileWriter fw = new FileWriter("out.txt", false); 
      BufferedWriter bw = new BufferedWriter(fw); 
      //將BufferedWriter與FileWriter物件做連結
      bw.write("Hello, my friend!");
      bw.newLine();
      bw.close();
    }
    catch (IOException e) {System.out.println(e);}
  }
}
```

## 讀入`a.txt`，加上行號後，再匯出`b.txt`
```java=
import java.io.*;

public class Week08 {
  public static void main(String[] args) { 
    /* 例外處理 */
    try { 
      FileReader fr = new FileReader("a.txt"); 
      BufferedReader br = new BufferedReader(fr); //緩衝區
      FileWriter fw = new FileWriter("b.txt", false); 
      BufferedWriter bw = new BufferedWriter(fw); 
      //將BufferedWriter與FileWriter物件做連結
      
      String line;
      int i = 1;
      while ((line = br.readLine()) != null) {
        line = "" + i + "  " + line; //將讀入的字串前面加入一個行號
        bw.write(line); //將帶有行號的字串寫入指定檔案
        bw.newLine();
        i++;
      }
      bw.close();
    }
    catch (IOException e) {System.out.println(e);}
  }
}
```
:::success
### HW06：檔案存取
* 將A檔案內容逐行讀入後，以相反順序輸出至B檔案
```java=
import java.io.*;

public class Week08 {
  public static void main(String[] args) { 
    /* 例外處理 */
    try { 
      FileReader fr = new FileReader("a.txt"); 
      BufferedReader br = new BufferedReader(fr); //緩衝區
      FileWriter fw = new FileWriter("b.txt", false); 
      BufferedWriter bw = new BufferedWriter(fw); 
      //將BufferedWriter與FileWriter物件做連結
      
      String line;
      int i = 1;
      
      String linelist [] = new String [10];
      while ((line = br.readLine()) != null) {
        linelist[i] =  i + "  " + line; //將讀入的字串前面加入一個行號
        System.out.println(linelist[i]);
        i++;
      }
      System.out.println();
      for (int j = 4; j > 0; j--) {
        System.out.println(linelist[j]);
        bw.write(linelist[j]); //將帶有行號的字串寫入指定檔案
        bw.newLine();
      }
      bw.close();
    }
    catch (IOException e) {System.out.println(e);}
  }
}
```

* 進階(動態宣告陣列長度)
```java=
import java.io.*;
import java.util.*;

public class Week08 {
  public static void main(String[] args) { 
    try { /* 例外處理 */
      FileReader fr = new FileReader("a.txt"); 
      BufferedReader br = new BufferedReader(fr); //緩衝區
      FileWriter fw = new FileWriter("b.txt", false); 
      BufferedWriter bw = new BufferedWriter(fw); 
      //將BufferedWriter與FileWriter物件做連結
      
      String line;
      int i = 1;
      
      Scanner sc = new Scanner(System.in);
      System.out.println("請輸入行數以宣告陣列大小：");
      int n = sc.nextInt();
      String linelist [] = new String [n+1];
      
      while ((line = br.readLine()) != null) {
        linelist[i] =  i + "  " + line; //將讀入的字串前面加入一個行號
        System.out.println(linelist[i]);
        i++;
      }
      System.out.println();
      for (int j = linelist.length-1; j > 0; j--) {
        System.out.println(linelist[j]);
        bw.write(linelist[j]); //將帶有行號的字串寫入指定檔案
        bw.newLine();
      }
      bw.close();
    }
    catch (IOException e) {System.out.println(e);}
  }
}
```
:::