---
# System prepended metadata

title: 找出兩個陣列中最大值

---

**2020/9/24**

https://hackmd.io/sWfBGJA3Shqa840FBbXdiQ?both
## 21

```
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {

    public static void main(String[] args) {
       int i,j,sum=0;
       int sale[] []={{1,2,3},{3,4,5,6}};
       for(i=0;i<sale.length;i++){
           System.out.print("業務員"+(i+1)+"的業績分別為");
           for(j=0;j<sale[i].length;j++){
               //System.out.print(sale[i][j]+" ");
               sum+=sale[i][j];
               //System.out.print(sum+",");
               //System.out.print(sum); 業務1=136 業務2=9131824
           }
           //System.out.print(sum); 業務1=6 業務2=24
           System.out.println("");
       }
           System.out.print(sum); //sum=24
    } 
    
```
   
----------------------------------------   

```
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {

    public static void main(String[] args) {
        Scanner scn=new Scanner (System.in);
        int n,i=1,sum=0;
        do{
            System.out.print("請輸入1-15:");
            n=scn.nextInt();
        } while(n<1||n>100);
            
        do{
            sum+=i++;
             System.out.printf("%d",sum);
             System.out.println("");
        }while(i<=n);
        System.out.printf("%d %n",sum);  
       
    } 
}
//input= 5  1+2+3+4+5=15
```

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

```
import java.util.Scanner;

public class Dowhile{
 public static void main (String arg[]){
   Scanner scn = new Scanner(System.in);
     int num,n,sum;
     do {
        System.out.print("請輸入1~15正整數來計算階乘值:");
     num = scn.nextInt();
     }while (num<1 || num>15);
     n=num;
     sum = 1;
     do {
        sum*= n--;
     }while (n > 0); 
     System.out.printf("%d! = %d %n",num,sum);

 }
}
//input=5 5!=120  5*4*3*2
```

```
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {

 public static void main (String arg[]){
  
   int[] score = new int[] {56,75,68,32};
   int p=0;
   for(int s : score){
     if (s >= 60)
        p++;
   }
   System.out.print(p);
 }
}

//input=2
```
```

package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {

 public static void main (String arg[]){
     int score[]={1,2,3,4,5};
     int i ,sum=0;
     for(i=0;i<score.length;i++){
       sum+=score[i];
       System.out.print(score[i]+",");
     }
     System.out.println("\n"+sum+","+sum/score.length);

 }
}

//input=1,2,3,4,5,
//input=15,3
```

```
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {

 public static void main (String arg[]){
 
   int i=1,w=5000;
   while(w>50)
   {
     w/=2;
     i++;
   }
   System.out.print("5000公升的水，一天漏一半，第"+i+"天會小於50公升");

 }
}

//output= 5000公升的水，一天漏一半，第8天會小於50公升
```

```
public class Exstr{
 public static void main (String arg[]){
   String[] exams = {"SCJP","SCWCD","SCMAD"};
   
   for(int i=0;i<=exams.length;i++){
     System.out.print(exams[i]+",");
   }
   System.out.println();
   
   for(String ex : exams){
     System.out.print(ex + ",");
   }
   System.out.println(); 
 }
}
```

```
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {

 public static void main (String arg[]){
 
    String[] exams = {"SCJP","SCWCD","SCMAD"};
   
   for(int i=0;i<exams.length;i++){
     System.out.print(exams[i]+",");
   }
   System.out.println();
   
   for(String ex : exams){
    System.out.print(ex + ",");
   }
   System.out.println(); 
 }
}


//Output=SCJP,SCWCD,SCMAD,
//Output=SCJP,SCWCD,SCMAD,
```

```
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {

 public static void main (String arg[]){
   int i,j,sum=0;
   int sale[] []={{32,35,26,30},{34,30,33,31}};
   for(i=0;i<sale.length;i++)
   {
     System.out.print("業務員"+(i+1)+"的業績分別為 ");
     for(j=0;j<sale[i].length;j++)
     {
        System.out.print(sale[i][j]+"  ");
        sum+=sale[i][j];
     }
     System.out.println();
   }
   System.out.println("\n 總銷售量為"+sum+"部車"); 
 }
}

業務員1的業績分別為 32  35  26  30  
業務員2的業績分別為 34  30  33  31  

 總銷售量為251部車
```

**2020/9/29**


```
import java.util.Scanner;
public class A {

    public static void main(String[] args) {
      String[] [] exams={{"Java","Python","PHP"},{"TQC","MTA","SCJP"}}; // 前面是第0列 後面是第1列
	for(String [] ex:exams){  //列
		for(String e:ex){ //行 跑列裡面的值
			System.out.print(e+",");
			
		}
	}
	System.out.println();
    } 
}
```


```
public class App03 {

	public static void main(String[] args) {
		String exam[] []= {{"JAVA","SCJSP"},{"SCWCD","SCMAD"}};
		
		A:
			for(String[] ex:exam)
			{
				B:
					for(String e:ex) {
						System.out.print(e+" ");
						continue A;
					}
					break;
		
			}
				System.out.println();
	}
}
```


```
public class App03 {

	public static void main(String[] args) {
		String exam[] []= {{"JAVA","SCJSP"},{"SCWCD","SCMAD"}};
		
		A:
			for(String[] ex:exam)
			{
				B:
					for(String e:ex) {
						System.out.print(e+" ");
						continue A;
					}
					break;
		
			}
				System.out.println();
	}
}
```

```
public class App04 {
	public static void main(String[] args) {
		int [][] n=new int[3][];
		n[0]=new int[] {1};
		n[1]=new int[] {2,3};
		n[2]=new int[] {4,5,6};
		for(int i=0;i<n.length;i++) {
			for(int j=0;j<n[i].length;j++)
				System.out.print(" "+n[i][j]);
			System.out.println();
		}
	}
}
```

```

public class App05 {
	public static void main(String[] args) {
		int [][] n= {{0,1,2,3},{4,5,6,7},{8,9,10,11}};
		int sum=0;
		for(int i=0;i<n.length;i++) {
			for(int j=0;j<n[i].length;j++) {
				System.out.print("n["+i+"]["+j+"]="+n[i][j]+",");
				sum+=n[i][j];
			//System.out.println(sum);
			}
			System.out.println();
		}
		System.out.println(sum);
	}
}
```

```

public class App07 { //Java 方法裡面不可以在宣告方法
	public static void main(String[] args) {
		star();
		System.out.println("Hello Java");
		star();
	}
	public static void star() {
		for(int i =0;i<=20;i++) {
			System.out.print("*");
		//System.out.println();
		}
	}
}
```


```

public class App09 {
	public static void main(String[] args) {
		double num;
		num=show_length(7,3);
		System.out.println(num);
		
		System.out.println(show_length(8,9));
	}
	public static double show_length(int i,int j) {
		
		return i*j;
	}
}
```


```
public class App08 {
	public static void main(String[] args) {
		int i ;
		i=foo(8);
		System.out.println(i);
		System.out.println(foo(10));
	}
	public static int foo(int n) {
		for(int i=1;i<2*n;i++)  
			System.out.print("*");
		System.out.println();
		return 2*n;
	}
}

```



```

public class App09 {
	public static void main(String[] args) {
		double num;
		num=show_length(7,3);
		System.out.println(num);
		
		System.out.println(show_length(8,9));
	}
	public static double show_length(int i,int j) {
		
		return i*j;
	}
}
```

```
public class App10 {
	public static void main(String[] args) {
		int num=10;
		add(num);
		System.out.println("main num:"+num);
	}
	public static void add(int n) {
		n=n+10;
		System.out.println("add n:"+n);
	}
}

```
傳2個數字比大小
2個數字丟到方法裡面
回傳最大的那個
再煮成是印出來

-----------------
10/4號
```
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {

 public static void main (String arg[]){
   
    Scanner sca=new Scanner(System.in);
    int a =sca.nextInt();
    int b=sca.nextInt();
    one(a,b);
   
 }
    public static int one(int a,int b){
        int max=0;
        if (a>b){
            max=a;
        }else{
            max=b;
        }
        System.out.print("最大的值是:"+max); 
        return max;
    }
}
```
**20201006**

```
public class App01 {
	public static void main(String[] args) {
		int A[]= {1,2,3,4,5};
		square(A);
		System.out.println();
	for(int i =0;i<A.length;i++) {
		System.out.println(A[i]);
	System.out.println();
	}
	}
	public static void square(int arr[]) {
		for(int i =0;i<arr.length;i++) {
			arr[i]=arr[i]*arr[i];
		}
	}
	
}
```



```
public class App02 {
	public static void main(String[] args) {
		int A[][]={{1,2,3,4,5},{6,7,8,9}};
		int B[][]=new int[2][];
		B[0]=new int[5];
		B[1]=new int[4];
		B=add10(A);
		for(int i =0;i<B.length;i++) {
			for(int j =0;j<B[i].length;j++)
				System.out.println(B[i][j]+" ");
				System.out.println();
			
		}
	}
		public static int[][] add10(int arr[][]){
			for(int i =0;i<arr.length;i++) 
				for(int j =0;j<arr[i].length;j++) 
				arr[i][j]+=10;
				return arr;	
		}	
}
```

傻眼貓咪



```
*註解

/**這是一個寵物的類別*/
public class Pet{

/**寵物的名稱*/

public static String name="小金";

/**寵物的品種*/

public static String type="金魚";

/**寵物的膚色*/

public static String color="金";

/**寵物的技能*/

public static void skill(){
            System.out.print("吐泡泡");
}}

在C槽路徑儲存Pet.java(選所有檔案)
cmd - javadoc -vercose -private Pet.java
```

```


package water;
public class Fish {
 public static String name="小金";
 public static String type="金魚";
 public static String color="金";
 public static void skill(){
     System.out.print("吐泡泡");
 }
}

public class Petastore{
   public static void main(String args[]){
     String fishName = water.Fish.name;
     String fishColor = water.Fish.color;
     String fishType = water.Fish.type;
    System.out.print("我有一之優雅的"+fishType+"，它叫"+fishName+"，它的顏色是"+fishColor+"色，每當它肚子餓的時候都會");
   water.Fish.skill();
 }
}
```
---------------------
**作業做不出來啊~~~~
粗東西~~~~~**
```
   public static void main(String[] args) {
        String[][] menu=new String[3][];
        String[] menu1= new String[3];
        Scanner sca = new Scanner(System.in);
        int a=sca.nextInt();
        int b=sca.nextInt();
        int c=sca.nextInt();
        menu[0]=new String[]{"凱薩沙拉","雞胸沙拉"};
        menu[1]=new String[]{"牛排","雞腿","海陸"};
        menu[2]=new String[]{"綠茶","咖啡","紅茶"};
        menu1[0]=menu[0][a-1];
        menu1[1]=menu[0][b-1];
        menu1[2]=menu[0][c-1];
	System.out.println("沙拉:"+menu1[0]+",主菜:"+menu1[1]+",飲料:"+menu1[2]);	
	}
}
```

# 找出兩個陣列中最大值


```
import java.util.Scanner;
public class NewClass {
	public static void main(String[] args) {
		int A[][]={{1,2,13,4,5},{6,10,8,9}};
		int B[][]=new int[2][];
		B[0]=new int[5];
		B[1]=new int[4];
		B=add10(A);
                int tmp=0;
                tmp=B[0][0];
		for(int i =0;i<B.length;i++) {
			for(int j =0;j<B[i].length;j++){                  
                                if(B[i][j]>tmp)
                                {
                                    tmp=B[i][j];
                                }      
				//System.out.println(B[i][j]+" ");
                        }    
		}
                System.out.print("Max="+tmp);  
	}
	public static int[][] add10(int arr[][]){
            for(int i =0;i<arr.length;i++)           
		for(int j =0;j<arr[i].length;j++) 
                    arr[i][j]+=10;             
                    return arr;	
		}	
}
```
# 1~100能被輸入的數字整除
```

import java.util.Scanner;
public class NewClass {
	public static void main(String[] args) {
                Scanner scn=new Scanner (System.in);
                int ab=scn.nextInt();  
                    if(ab<100 && ab>1){
                        for(int i=1;i<=100;i++){
                            if(i%ab== 0) {
                                System.out.println(i+"");  
                            }
                        }     
                    }else{
                        System.out.println("Error Enter");  
                    }
    }       
            
}
```
**1
22
333
4444
55555**
```
import java.util.Scanner;
public class NewClass {
    public static void main(String[] args) {
 
    for(int i=1;i<=5;i++) { 
        for(int j=1;j<=i;j++) {   
            System.out.print(i); 
        }    
            System.out.println();   
    }    
    }
}
```

# `10-13`
```
//類別
class CRectangle{  //沒有就是default
    int width; //屬性
    int height;
}

default 同個package才可以存取 不可透過繼承
public class App01{ // 只能有一個public 因為跟類別名稱一樣
    
}
```
```

class CRectangle{  
    int width; 
    int height;
    int area(){
	    return width*height;
}
public class App01 {
	public static void main(String[] args) {
		CRectangle c=new CRectangle();
		c.width=10;
		c.height=20;
		System.out.println("width="+c.width);
		System.out.println("height="+c.height);
		System.out.println(area());
		//area(c.width,c.height);
	}/*
	 int area(){
		
		return width*height;
	 }*/

	
	public static int area(int a,int b) {
		System.out.println(a*b);
		return a*b;
		
	}
}
```

```
class Car{
	String type;
	int speed;
	int speed() {
		return speed;
	}
}
public class App_02 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Car b = new Car();
        b.type = "BMW" ;
        b.speed= 220;
        Car t = new Car();
        t.type = "Toyota" ;
        t.speed= 180;
        System.out.println(b.type+" "+b.speed);
        System.out.println(t.type+" "+t.speed());
	}

}
```

Constructor建構子
建立物件時，除了在記憶體中配置區塊外，同時也會執行建構子涵式，它是建立物件時第一個被執行的函數

1.建構子沒有傳回值
2.建構子名稱必須和類別名稱相同

預設建構子
1.new 一個物件時，會自動執行
2.每一個class最多只一個預設建構子(預設的看不到)
3.程式中沒有自行定義建構子時，執行時就會自動加入
4.預設建構子沒有參數列

**只要有new就一定會有建構子
Test t =new Test();
         //配置記憶體區塊放這個物件
         

```
class Car{
	String type;
	int speed;
	int BMW;
	int Toyota;
	int speed() {
		return speed;
}}
public class App02 {
	public static void main(String[] args) {
		Car c=new Car();
		Car c1=new Car();
		c.type="BMW";
		c.speed=210;
		
		c1.type="Toyota";
		c1.speed=180;
		System.out.println(c.type+" "+c.speed());	
		System.out.println(c1.type+" "+c1.speed());
		
	}
}
```
```


public class App03 {
	public App03(){ // 根類別名稱一樣  沒有資料行別跟傳回值
		System.out.println("我是App03自己定義的建構子");
	}
	public static void main(String[] args) {
		App03 a=new App03();//
		new App03(); //前面要加new  這邊也會同時執行建構子   new 時建構值會同時執行
	}
	}
}
```


```
public class App_04 {
	char size;
	int price;
	public App_04(char s,int p )//這裡定義字元+整數
	{
		size=s;
		price=p;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		App_04 t=new App_04('L',350);//這裡順序不可以調換(字元+整數)
		System.out.println("size:"+t.size);
		System.out.println("price:"+t.price);
 
	}

}
```


```
public class App_05 {
	String type;
	int speed;
	public App_05(String t,int s )
	{
		type=t;
		speed=s;
		System.out.println("Type:"+type);
		System.out.println("Speed:"+speed);
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		App_05 t1=new App_05("BMW",220);
		App_05 t2=new App_05("Toyota",180);
 
	}

}
```

overloading覆載

指同一種方法名稱根據不同的參數型別，以對應執行不同的實作

建構子的overload
Test(){}
Test(Steing a,int b){}
Test(int b,String a){}
Test(String a){}

方法的overload
void foo (){}
void foo (String a,int b){}
void foo (int b,String a){}
void foo (String a){}


//overload function
public class App_06 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		star();
		star(7);
		star('*',9);
	}
	public static void star() {
		star(5);
	}
	public static void star(int n) {
		for(int i=1;i<=n;i++)
			System.out.print('@');
		System.out.println();
	}
	public static void star(char ch, int s) {
		for (int i=1;i<=s;i++)
			System.out.print(ch);
		System.out.println();

	}
    //不可以再寫一個一樣的public static void star(char a, int b)，即使名稱不一樣
}

```
class Car{
	double gs;
	double ts;
	double max;

public Car() {
	System.out.println("Car()");
}
public Car(double g,double t) {
	gs=g;
	ts=t;
	dist();
}
public void dist() {
	max=gs*ts;
	System.out.println(max);
}}
public class App06 {
	public static void main(String[] args) {
		Car c=new Car();
		Car c1=new Car(64.5,9.2);
	}
}
```


**2020/10/15**
```
class Cavg{
	public double getAvg(int num1,int num2) {
		return (num1+num2)/2;
	}
	public double getAvg(int[] vArray) {
		int n =vArray[0];
		for (int i=1;i<vArray.length;i++) {
			n+=vArray[i];
		}
		double avg=(double)n/vArray.length;
		return avg;
	}
}
public class App_01 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	     	Cavg num=new Cavg();
	     int n1 =20,n2=30;
	     System.out.println(n1+"和"+n2+"平均值為"+num.getAvg(n1,n2));
	     int[]ary = {12,23,31,45,56};
	     System.out.println("{12,23,31,45,56}平均值為"+num.getAvg(ary));

	}

}
```
# `1015`

```
class Cavg{

	public  double getAvg(int num1,int num2) {
		return(num1+num2);
	}
	public double getAvg(int[] vArray) {
		int n = vArray[0];
		for(int i=1;i<vArray.length;i++) {
			n+=vArray[i];
		}
		double avg =(double)n/vArray.length;
		return avg;
	}
}
public class App01 {
	public static void main(String[] args) {
		Cavg num=new Cavg();
		int n1=20,n2=30;
		int [] ary= {12,13,14,15,16};
		System.out.println("平均值為"+num.getAvg(ary));
	}
}
```


```
public class App02 {
	public static void main(String[] args) {
		
		int a= newCale(1,2);
		int b= newCale(1,2,3,4);
		int c= newCale(a,b);
		System.out.println(c);
	}
	public static int newCale(int...c) {  //...表示型別是陣列   //static 在global 全部都能用  沒有宣告實體  new 
		int sum=0;                       //有太多static 與全域變數會很吃效能
		for(int i:c) {
			sum+=i;
		}
		return sum;
	}
}
```
繼承
指類別誤鍵的資源可以延伸
和重複使用，在程式中可用extends
來代表繼承關係
這種延伸類別的關係也是"is a"的概念

```

class Father{
	public int money=4500000;
	public void undertaking() {
		System.out.println("父親的事業");
	}
}
class Son extends Father{
	
}
public class App03 {
	public static void main(String[] args) {
		Son son = new Son();
		son.undertaking();
		System.out.println(son.money);
	}
}
```

```
//利用建構子傳值
class Father{
	int money;
	//public int money=4500000;
	public void undertaking() {
		System.out.println("父親的事業");
	}
}
class Son extends Father{
	Son(int p){
		money=p;
	}
}

public class App03 {
	
	public static void main(String[] args) {
		Son son = new Son(1000000);
		son.undertaking();
		System.out.println("金額:"+son.money);
	}
}

```

this,super 關鍵字
this 可以參考到目前使用中該物件的
屬性、方法、建構子
super 可以參考到父物件的屬性、方法、建構子,指的是類別自己

所以super必須在繼承關係下(因為參考爸爸的方法)

撰字時需注意
1.若要利用this呼叫建構子，需將this放在第一行
super也一樣
public Test(){
   this(5);
   程式敘述
   
}
2.避免this和super出現在同一個方法

物件指的是當前的class (this)

```
class Father1{
		Father1(char c){
			System.out.println(c);
		}
	
}
class Son1 extends Father1{
	Son1(){//建構子 //2
		this('A'); //3
		System.out.println("B");
	}
	Son1(char c){ //4
		super(c); //5
	}	
}


public class App05 {
	public static void main(String[] args) {
		Son1 son = new Son1(); //1
		
	}
}
```

```
//隱含式的super
class Father2{
		Father2(){ //僅限於沒有參數的建構值 如果有(String s) 就會錯
			System.out.println("A");
		}
	
}
class Son2 extends Father2{
	Son2(){//建構子  //這邊會執行隱含式的super
		
		System.out.println("B");
	}	
}


public class App06 {
	public static void main(String[] args) {
		Son2 son = new Son2();
		
	}
}

```
```
class App_05{
	int i=100;
	int j=200;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		App_05 t = new App_05();
		t.amethod();

	}
	void amethod() {
		int i=50;
		int j=30;
		System.out.println(this.i);//改成t.i的話找不到
		System.out.println(this.j);
		System.out.println(i);
		System.out.println(j);
	}

}
```
Static法方中並沒有this和super的參照
當然不可以在static方法實作區塊中下
this 或super 指令

```
class Cperson{
	private int age;
	public static void setAge(int age) {
		//this.age=age;
		age=age+2;
		System.out.println(age);
		//System.out.println(this.age);
		
	}
}
public class App08 {
	public static void main(String[] args) {
		Cperson j=new Cperson();
		j.setAge(20);
	}
}

```

static &non_static 
1.static method 使用時 不用物件實體就可以直接呼叫他

不需要new就可以呼叫

2.non_static method使用時 沒static 一定要new
需要new 才可以呼叫



# `1020`

```
//this super 
class Father{
	public int money=50000000;
	public void undertaking() {//(12)
		System.out.println("父親的事業:房地產");
	}
}
class Son extends Father{
	public int money;
	public int money1;
	Son(int money){ //(2)
		//money1=money;
		//this.money=money; 方法1
		setMoney(money); //(3)
	}

public void setMoney(int money) { //(4)
	this.money=money; //(5)
}
public void undertaking() { //(9)
	System.out.println("兒子的事業:電腦網路");
}

public void go() { //(7)
	undertaking(); //(8)兒子
	System.out.println("市值"+money); //方法1 money money1  (10)
	super.undertaking(); //(11)
	System.out.println("市值"+super.money); //(13)
}
}
public class App01 {
	
	public static void main(String[] args) {
		 new Son(1000000).go(); // (1).new  (6)go.()
	
	}
}

```

```
static 成員與non static成員 溝通法則

non static可存取non static和static成員
static 成員只允許存取static成員 若要存取non static
成員，必須建立物件後才可以使用
```
```
public class App03 {
	public static void main(String[] args) {
		new App03().amethod();
	}
	void amethod() {
		bmethod();
		cmethod();
		System.out.println("amethod()");
	}
	void bmethod() {
		System.out.println("bmethod()");
	}
	static void cmethod() {
		dmethod();
		//bmethod(); static 無法存取 non static 
		System.out.println("cmethod()");
	}static void dmethod() {
		System.out.println("dmethod()");
	}
}
```
陣列物件
1.使用java.util.Arrays的fill() util package 
  方法設定新陣列的元素值
2.陣列複製也可透過Arrays/copyOf()方法

```
import java.util.Arrays;
public class App04 {
	public static void main(String[] args) {
	int scores[]=new int[10];
	for(int score:scores)
		System.out.printf("%2d",score);
		System.out.println();
		Arrays.fill(scores,60);
		
		for(int score:scores)
			System.out.printf("%3d",score);	
	}	
}
```

```
import java.util.Arrays;
public class App05 {
	public static void main(String[] args) {
	int score1[]= {1,2,3,4,5};
	int score2[]= Arrays.copyOf(score1, score1.length);//透過copyOf的會新增新的記憶體
	for(int score:score2)
		System.out.printf("%2d",score);
		System.out.println();
		score2[0]=99; //原本改址a的值會跟著改變 但這個複製方法是在建一個記憶體位置
	for(int score:score1)
		System.out.printf("%2d",score);
		System.out.println();
	for(int score:score2)
		System.out.printf("%2d",score);
	}
}

```
override 覆寫
發盛在繼承關西中，子類別自行實做一個方法名稱與父類別相同
程式執行時會執行子類別不會執行父類別

//
1.必須是繼承關西
2.覆寫的方法名稱必須相同
3.方法的參數列(不論數量，順序，型別)都必須相同  方法如果是 int a  另一個方法就也要是  int a  但變數名稱可變
4.存取權限不可以小於原方法(可大於或等於)
5.若有回傳形態也必須相同或是原型別的子類別

```

class Father2{
	 int aMethod() { //protected public 都比default大      父類別如果是static不能覆寫
		return 2;
	}
}
class Son2 extends Father2{
	Son2(){
		System.out.println(super.aMethod());
	}
	public int aMethod() {
		super.aMethod();
		return 3;
	}
}
public class App06 {
	public static void main(String[] args) {
	Son2 s=new Son2();
	Father2 s1=new Father2();
	System.out.println(s.aMethod());
	System.out.println(s1.aMethod());
	}
}
```

```
上面的另一種寫法，一定要印出父類別的方法
class Father1{
	int aMethod() {
		return 2;
	}
}
class Son1 extends Father1{
	Son1(){//建構子
		System.out.println(super.aMethod());
	}
	public int aMethod() {
		return 3;
	}
}
public class App_05 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Son1 s= new Son1();
		System.out.println(s.aMethod());
		
	}

}
```

```
public class RPG {
	public static void main(String[] args) {
		SwordsMan swordsMan=new SwordsMan();
		swordsMan.setName("Justin");
		swordsMan.setLeval(1);
		swordsMan.setBlood(200);
		
		Magican magican=new Magican();
		magican.setName("magican");
		magican.setLeval(1);
		magican.setBlood(100);
		drawFight(swordsMan);
		drawFight(magican);
	}	
	static void drawFight(Role role){
		System.out.println(role.getName());
		role.fight();
	}
}
```


```
public class Magican extends Role{

	@Override
	public void fight() {
		System.out.println("魔法攻擊");
		//super.fight();
	}
	public void cure() {
		System.out.println("魔法治療");
	}
	@Override
	public String toString() {
		  return "魔法師"+super.toString();
		//return super.toString();
	}
	
}

```

```
public class SwordsMan extends Role{

	@Override
	public void fight() {
		System.out.println("揮劍攻擊");
		//super.fight();
	}

	@Override
	public String toString() {
		//return super.toString();
		return "劍士"+super.toString();
	}

	
}
```
```
public class Role {
	protected String name;
	protected int leval;
	protected int blood;
	public void fight(){}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getLeval() {
		return leval;
	}
	public void setLeval(int leval) {
		this.leval = leval;
	}
	public int getBlood() {
		return blood;
	}
	public void setBlood(int blood) {
		this.blood = blood;
	}
	
	public String toString() {
		return String.format("(%s,%d,%d",this.name,this.leval,this.blood);
	}
}



```
//封裝
透過統一方法或介面實作 取得那些類別中不被外部直接
存取的那些資料 維護物件 資源的完整

public class En_class 

overloading 在繼承底下方法相同
override 方法名稱相同 不一定要繼承

private 存取權限 同一個class 底下

# 10-22

```
//利用封裝的方式
public class Enc_class {
	public static void main(String[] args) {
		MyAcount account =new MyAcount();
		account.setMoney(100000);
		System.out.println("$"+account.getMoney());
	}
}
	class MyAcount{
		private int money;
		public void setMoney(int money){
			this.money=money;
		}
		public int getMoney(){
			return money;
		}		
	}

```
```

import java.util.Scanner;
public class CardApp {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner s=new Scanner(System.in);
		CashCard c1 = new CashCard("A001",500,0);
		CashCard c2 = new CashCard("A002",300,0);
		CashCard c3 = new CashCard("A003",1000,1);
		c1.store(s.nextInt());
		c2.store(s.nextInt());
		c3.store(s.nextInt());
		System.out.printf("明細- 名字:%S 餘額:%4d 元,紅利:%d %n",c1.getNumber(),c1.getBalance(),c1.getBonus()); 
		System.out.printf("明細- 名字:%S 餘額:%4d 元,紅利:%d %n",c2.getNumber(),c2.getBalance(),c2.getBonus()); 
		System.out.printf("明細- 名字:%S 餘額:%4d 元,紅利:%d %n",c3.getNumber(),c3.getBalance(),c3.getBonus()); 

	}

}
```


```

public class CahCard {
	private String number;
	private int balance;
	private int bonus;
	
	public CahCard(String number, int balance, int bonus) {
		
		this.number = number;
		this.balance = balance;
		this.bonus = bonus;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	public int getBalance() {
		return balance;
	}
	public void setBalance(int balance) {
		this.balance = balance;
	}
	public int getBonus() {
		return bonus;
	}
	public void setBonus(int bonus) {
		this.bonus = bonus;
	}
	void store(int money) {
		if(money>0) {
			this.balance+=money;
			if(money>=1000) {
				this.bonus++;
			}
		}
		else {
			System.out.println("餘額是負的來亂的嗎");
		}
	}
	
}
```

```
class Ccar{
	private double gas,tbo;
	private double max;
	private void Maxdist() {
		max=gas*tbo;
	}
	public void setValue(double g,double t) {
		this.gas=g;
		this.tbo=t;
		Maxdist();
	}
	public double getValue() {
		return max;
	}
}
public class Enc2class {
		public static void main(String[] args) {
			Ccar c1=new Ccar();
			double g1=40,t1=13.6;
			c1.setValue(g1, t1);
			System.out.println(c1.getValue());
			
	}
}
```

```
final 
類別宣告成final 不能被extends

final class Test{}

方法被/*

final class App01 { //無法被繼承
	int weight;
}


class Ccar{
	private final int speed=120; //final 一定要有值
	//final int a=10; //final 無法更改值
	//int b=20;
	//a=b;
	public final void show(String s) {
		System.out.println(speed);
	}
}
class App02 extends Ccar{ //無法繼承App01
	//public void show(String s) {  final 無法override
	//}
}


```

多型
泛指在只有繼承的關係架構下,單一實體可以宣告成多種型別
Animal a=new Cat();

```
//父類別被子類別包住
class Animal{
	void move() {
		System.out.println("移動");
	}
}
class Cat extends Animal{
	public void move() {
		System.out.println("Cat移動");
	}
	void skill(){
		System.out.println("抓老鼠");
	}
}
class Tiger extends Cat{
	public void skill(){
		System.out.println("老虎");
	}
}
public class App02 {
	public static void main(String[] args) {
		Animal a=new Cat();
		//a.skill(); 以父親的觀點
		a.move();
		Cat c=new Tiger();
		c.skill();
		c.move();
		Animal t=new Tiger();
		//t.skill(); 以父親的觀點
		t.move();
	}
}
```

# 10-29
```

class Father{
	String name="Father";
	String geting() {
		return "class Father";
	}
}
class Son extends Father{
	String name="Son";

String geting() {
	return "class Son";
}

void foo() {
	System.out.println();
	System.out.println(name); //this.son
	System.out.println(super.name); //super.name
	System.out.println(((Father)this).name); //this.name
	System.out.println(this.geting()); //
	System.out.println(((Father)this).geting()); //這邊有轉型但override 所以還是印兒子的
	
}}
public class App04 {
	public static void main(String[] args) {
		new Son().foo();
		
	}
}
```
```

class Iattack{
	void showAttack() {
		
	};
}
class Cspider extends Iattack{
	public void showAttack() {
		System.out.println("蜘蛛人的攻擊力:60");
		System.out.println("攻擊方式會發射蜘蛛網");
	}
}
class CSuperMan extends  Iattack{
	public void showAttack() {
		System.out.println("蜘蛛人的攻擊力:100");
		System.out.println("攻擊方式使用拳頭");
	}
}
public class App05 {
	public static void main(String[] args) {
		Iattack a=new Cspider();
		Iattack b=new CSuperMan();
		a.showAttack();
		b.showAttack();
	}
}
```

//interface 介面

介面也是類別的一種,利用相同機會介面
可讓程式選字時有一定的規則可循
可以利用介面來搜集多個類別

介面宣告
存取權限 interface介面名稱
介面中的屬性必須有初始值
因為在compile時，編譯器會自動加上public static final 

2.介面中的方法不可以有實作區區塊
  void skill();
3.利用implement 實作interface
  存取修飾元class 類別implements 介面1,介面2

4.interface 可以解單一繼承問題
5.介面中不可以有一般方法; //有實作區塊的方法{}
6.實作介面時必須把所有的方法都加以實作
7.介面中的方法都是
public abstract void 方法名稱() //像是預設建構值一樣

```
interface pet{
	String attr="cute";
	void skill();
	void move();
}

public class App06 implements pet {
	public void skill() { //實作
		System.out.println("拿報紙");
	}
	public void move() { //實作
		System.out.println("移動");
	}
	
public static void main(String[] args) {
	App06 d=new App06();
	d.skill();
	d.move();
}}
```


```
interface Animall{
	String name_show();
	String color_show();
	
}
public class App07 implements Animall {
	public String name_show() { //實作
		return "小黑";
	}
	public String color_show() { //實作
		return "black";
	}
	
public static void main(String[] args) {
	App07 d=new App07();
	System.out.println("我有一隻狗名叫:"+d.name_show()+"皮膚的顏色是:"+d.color_show());
}
}
```


```
interface iShap{
	double pi=3.14;
	void setColor(String s);
}

interface iShap2D extends iShap{
	void area();
}
class Circle implements iShap2D{  //Circle在繼承iShap2D   而iShap2D繼承iShap 固都能使用
	double r;
	String c;
	Circle(double r){
		this.r=r;
	}
	public void setColor(String c){
		this.c=c;
		System.out.println(c);
	}
	public void area() {
		System.out.println(r*r*pi);
}}
public class App09 {
	public static void main(String[] args) {
		Circle c=new Circle(6.0);
		c.setColor("Blue");
		c.area();
	}
}
```
```
interface iShap{
	double pi=3.14;
	void setColor(String s);
}

interface iShap2D extends iShap{
	void area();
}
class Circle implements iShap2D{  //Circle在繼承iShap2D   而iShap2D繼承iShap 固都能使用
	double r;
	String c;
	Circle(double r){
		this.r=r;
	}
	public void setColor(String c){
		this.c=c;
		System.out.println(c);
	}
	public void area() {
		System.out.println(r*r*pi);
}}
public class App09 {
	public static void main(String[] args) {
		Circle c=new Circle(6.0);
		c.setColor("Blue");
		c.area();
	}
}
```
```

interface ICircle{
	public static final double pi=3.14;
	void show();
	void area();
}
interface Icolor{
	void draw(int i);
}
class Cshap{
	public double area=2;
	public void show() {
		System.out.println("area="+area);
	}
}
class Circle1 extends Cshap implements ICircle,Icolor{
	double radius;
	Circle1(double r){
		radius=r;
	}
	
	public void area() {
		System.out.println("area="+radius*radius*pi);
	}
	public void draw(int i) {
		if(i==0)
			System.out.println("Blue");
		else if(i==1)
			System.out.println("Red");
		else 
			System.out.println("Error");
	}
}

public class App10 {
	public static void main(String[] args) {
		Circle1 c=new Circle1(2.0);
		c.area();
		c.draw(2);
		c.show();
	}
}
```

# 11-03

*JAVA是單一繼承
*寫成是要注意耦合性

----------------------------------
```
public interface Swimmer {
	public void swim();
	
}
```
```
public interface Driver extends Swimmer{
	public void driver();
}

```

```
public interface Flyer {
	public void fly();
	
}


```
![](https://i.imgur.com/vZqqfTN.jpg)
```

public class Fish implements Swimmer{
		protected String name;
		public Fish(String nmae) {
			this.name=name;
		}
		public String getName() {
			return name;
		}
		@Override
		public void swim() {
			// TODO Auto-generated method stub
			
		}
		
}





```

1111111111111111111111111111111111111


```

public class FlyingFish extends Fish implements Flyer{
	public FlyingFish(String name) {
		super(name);
	}

	
	
	@Override
	public void swim() {
		System.out.printf("飛魚游泳");
	}



	@Override
	public void fly() {
		System.out.printf("飛魚會飛");
	}
	

}

```

```
public class Piranha extends Fish{
	public  Piranha(String name) {
		super(name);
	}

	@Override
	public void swim() {
		
		System.out.printf("食人魚%s",name);
	}
	
}
```

```
public class Anemonefish extends Fish{
	public  Anemonefish(String name) {
		super(name);
	}

	@Override
	public void swim() {
		System.out.printf("小丑魚%s游泳",name);
	}
}

```
```

public class shark extends Fish{
	public shark(String name) {
		super(name);
	}

	
	@Override
	public void swim() {
		// TODO Auto-generated method stub
		System.out.printf("鯊魚%s",name);
	}
	
}

```


222222222222222222222222


```
public class Airplane implements Flyer{
	protected String name;
	public Airplane(String name) {
		this.name=name;
	}
	@Override
	public void fly() {
		System.out.printf("飛機%s在飛%n",name);
		
	}
	
}
```
```

public class Seaplane extends Airplane implements Swimmer{
	public Seaplane(String name) {
		super(name);
	}

	@Override
	public void swim() {
		System.out.printf("海上飛機%s航行海面%n",name);
		
	}

	@Override
	public void fly() {
		System.out.printf("海上");
		super.fly();
	}
	
}
```
3333333333
```

public class Human {
	protected String name;
	public Human(String name) {
		this.name=name;
	}
	public String getName() {
		return name;
	}
}


```

```
public class SwimPlayer extends Human implements Swimmer{
	public SwimPlayer(String name) {
		super(name);
	}

	@Override
	public void swim() {
		System.out.printf("游泳選手%s游泳%n",name);
		
	}

}

```
```

public class App01  {
	public static void main(String[] args) {
	doSwim(new Anemonefish("尼莫"));
	doSwim(new shark("藍尼"));
	doSwim(new SwimPlayer("獎斯汀"));
	doSwim(new Seaplane("空軍零號"));
	doSwim(new FlyingFish("甚平"));
	dofly(new Airplane("飛飛飛飛"));
	dofly(new Seaplane("雞雞雞雞雞雞"));
	dofly(new FlyingFish("高高高高高高"));
	}
	static void doSwim(Swimmer s) {
		s.swim();
	}
	
	static void dofly(Flyer f) {
		f.fly();
	}
}	
```
abstract 抽象類別
抽象類別是為了讓方法的使用更多樣化
抽象類別的宣告 {
abstract class 類別名稱{}
抽象類別中的抽象方法宣告
存取修飾元 abstract 傳回值 方法名稱("無實作");
一般類別:只能有時作區塊的方法
class A{
  void amethod(){}
}
介面:只能有無實作區塊的方法
interface B{
  void amethod();//public abstaract
}
抽象類別:可以有無實作和有實作區塊的方法
abstaract class{
abstaract void amthod();
void bmethod(){}
}
子類別 可用extends 關鍵是作為父類別


```
abstract class Puppy{
	abstract void skill();
	public void play() {
		System.out.printf("我想出去玩");
	}
}
public class Dog extends Puppy{ 
	public static void main(String[] args) {
		Dog d=new Dog();
		d.skill();
		d.play(); //extend 繼承的概念
	}
	public void skill() {   //實作抽象類別
		System.out.printf("拿報紙");
	}
}



```

抽象類別abstract 
1.不可以是private
2.抽象類別中可以有實作區塊和無實作區塊
3.抽象類別要extends抽象父類別
4.抽象類別透過override方式實作父類別的抽象方法


```
abstract class Line {
	private int length;
	public Line(int a) {
		length=a;
	}
	int getLength() {
		return length;
	}
	abstract double area();
}
public class Son extends Line{
	public Son(int a) {
		super(a);
	}
public static void main(String args[]) {
	Son s=new Son(8);
	System.out.println("area="+s.area());
}
public double area() {
	return Math.pow(getLength(), 2);
}}

```
列舉 enum

enum 就是類別 可以單獨選字
也可以寫在類別內當成內部類別，稱之為enum inline
1.enum Week {..}是一個類別
2.public abstract class Enum 可以是抽象的
3.public final class Week extends Enum 直接繼承

4.enum 的內容都是public static ,final (class 加final 就不能被繼承

方法不可以被override
不可以被更改) 
5.列舉一經宣告就無法更改
6.列舉可以用==or equals 來比較
7.列舉的內容值就是該列舉的型別

一.透過
```
public class EnumClass {
	public enum Week{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Satursday}
	public static void main(String args[]) {
		System.out.println(Week.Sunday); //1.透過.    Week 是他的型別
		
		Week week=Week.Sunday;
		System.out.println(week.Sunday); //2.透過參照
		
		Week[] week2=Week.values(); //3.透過values
		for(int i=0;i<week2.length;i++) {
			System.out.print(week2[i]+" ");
		}
		
	}
	
}

```

```
enum Grod{A{
	public String toString(){
		return "String";
	}},B,C,D}

public class EnumTest {
	public static void main(String args[]) {
		System.out.print(Grod.A);
		System.out.print(Grod.B);
	}
}




```
星期一猴子穿新衣
星期二猴子去烤肉
星期三猴子去爬山

```

public class TestTestSee {
	public enum Week{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Satursday}
	public static void main(String args[]) {
		//System.out.println(Week.Monday); //1.透過.    Week 是他的型別
		switch(Week.Monday){
		case Monday:
			System.out.println("星期一猴子穿新衣");
			break;
		
		case Tuesday:
			System.out.println("星期二猴子吃山山");
			break;
		
		case Wednesday:
			System.out.println("星期三猴子烤肉肉");
			break;
		}
	}
}
	
```

inner class 內部類別
類別中在定義一個類別 其宣告位置
與存取可分為下列四種:
1.內部類別
2.方法類別
3.匿名類別
4.靜態內部類別

```

public class OuterClass {
	class Inner1{
		class Inneragin{
			
		}
	}
	class Inner2{
		
	}
	class Inner3{
		
	}
}
```
```

public class InnerTest {
	public static void main(String args[]) {
		Outer ou=new Outer(); //new 的是兩個不同的實體
		Outer.Inner oi=ou.new Inner();//記憶體在不同的區塊
		                              //new 匯出一個新的記憶體位置
		oi.callMe();
	}
}

```


public class MyOuter {
	private static int sx=9;
	private int x=7;
	class MyInner{
		private int x=77;
		public void callMe() {
			int x=777;
			System.out.println("Local x="+ x);
			System.out.println("MyInner x="+ this.x );
			System.out.println("MyOuter x="+ MyOuter.this.x );
			System.out.println("sx="+sx);
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new MyOuter().new MyInner().callMe();

	}

}


https://hackmd.io/EvA0qa06S0CZuIAGQ9nN-w


2021-11-19
```

匿名類別
簡單說就是沒有宣告名稱的類別
直接以new 關鍵字來建立類別實體
適用時機是在整個城市中只用到一次之後便不在使用

宣告方式
new 類別或介面名稱{};

```

```
```
Error，Exception，Throwable
Error=通常是指系統本身發出的錯誤訊，也有可能是程式造成

Exception 程式執行期間不正常所以引起的錯誤
Thowable error
Thowable exception

try -catch

try{
    //statement 
}catch(FileNotFoundException e){
    //statement
}catch(Exception e){
    //statement
}

```
public class ExceptionSample {
	static int num=20;
	static int arr[]={0,2,4};
	static String answer;
	public static void main(String args[]) {
		try {
			calc(0);
		}catch(Exception e) {
			System.out.println(e.getMessage());
		}
			//System.out.println(num+"/"+arr[0]+"="+num/arr[0]);
	}
	public static void calc(int a)throws Exception{
		double ans=0;
		if((a==0)||(a>=arr.length))
		{
			answer="無法計算";
			throw new Exception("傳入數值不得為:"+a);
		}
		ans=num/arr[a];
		answer=String.valueOf(ans);
}}
```
```

import java.util.InputMismatchException;
import java.util.Scanner;

public class Average {
	public static void main(String args[]) {
		Scanner scanner=new Scanner(System.in);
		double sum=0;
		int count =0;
		int number;
		
		while(true) {
			try {
			number = scanner.nextInt();
			if(number==0) {
				break;
			}
			sum+=number;
			count++;
			}catch(InputMismatchException ex) {
				System.out.println("");
			}
			System.out.printf("率過非整數%s%n",scanner.next());
	}
	}
}
```
```

public class MultiException {
	public static void main(String args[]) {
		int [] myarr=new int[10];
		try {
		int test=120/5;
		myarr[20]=125;
		int n=Integer.parseInt("你好嗎");
		
	}catch(Exception e) {
		System.out.println("例外內容:"+e.toString());
		System.out.println("例外發生");
	}
	CA	
		
}
```

# `11-24`

```
利用throw 丟出例外
throw 是用來呼叫或傳遞一個例外
所以可以利用他在程式中觸發一個例外

程式語法
a.throw 例外物件變數
丟出一個例外物件變數
b.throw new Ecxception (錯誤訊息字串)
丟出一個匿名例外物件

import java.util.Scanner;
public class ThrowDemo {
	static void math_div(int n1,int n2) {
		try {
			if(n2==0) 
				throw new ArithmeticException("除數為零");
				int div=n1/n2;
				System.out.println(n1+"/"+n2+"="+div);
			
			}catch(ArithmeticException e) {
				System.out.println("例外內容="+e.toString());
		}
	}
	public static void main(String args[]) {
		//int num1=6,num2=3;
		Scanner scn=new Scanner (System.in);
		int num1,num2;
		num1=scn.nextInt();
		num2=scn.nextInt();
		System.out.println("被除數="+num1+",除數="+num2);
		math_div(num1,num2);
	}
}
```

Exception Constructor 

我們可以利用Exception 建構子自訂錯誤訊息
定義
1.Exception ()
預設建構值

2.Exception(String message)
自行定義的錯誤訊息傳入

3.Exception(String message,Throwable cause)
將自行定義的錯誤訊息和導致發生的原因傳入
4.Exception (throwable cause)
將導致發生的原因
強化學習

利用throw 自訂例外方法
撰寫成事實，若方法中會產生例外處理
宣告方式
方法名稱(參數列)
```

import java.util.Scanner;
public class ThrowDemo {
	static void math_div(int n1,int n2) {
		try {
			if(n2==0) 
				throw new ArithmeticException("除數為零");
				int div=n1/n2;
				System.out.println(n1+"/"+n2+"="+div);
			
			}catch(ArithmeticException e) {
				System.out.println("例外內容="+e.toString());
		}
	}
	public static void main(String args[]) {
		//int num1=6,num2=3;
		Scanner scn=new Scanner (System.in);
		int num1,num2;
		num1=scn.nextInt();
		num2=scn.nextInt();
		System.out.println("被除數="+num1+",除數="+num2);
		math_div(num1,num2);
	}
}

```

```
import java.io.*;
public class InputDemo {
	public static void main(String args[])throws IOException {
		String str;
		int num,sum=0;
		int i=1;
		BufferedReader buf;
		//buf=new BufferedReader(new InputStreamReader(System.in));
		
		do {
			 buf=new BufferedReader(new InputStreamReader(System.in));
			 System.out.println("請輸入整數");
			 str=buf.readLine();
			 num=Integer.parseInt(str);
			 
		     }while (num<1 || num>101);
		
		   	do{
	            sum+=i++;
	             //System.out.printf("%d",sum);
	             //System.out.println("");
	        }while(i<=num);
	        System.out.printf("%d %n",sum);  
	       
	    } 
	}
	//1以下100以上 重新輸入 如果是內加總



```
```

這個是界面阿 好有趣喔喔喔

import java.io.*;

import javax.swing.JOptionPane;
public class SwingDemo {
	public static void main(String args[]) {
		String str=JOptionPane.showInputDialog("請輸入:");
		int num=Integer.parseInt(str);
		JOptionPane.showMessageDialog(null,num*num);
	}
}

```

```

public class FinallyDemo {
	public static void main(String args[]) {
		int[] myarray=new int[10];
		try {
			myarray[20]=120;
		}catch(ArrayIndexOutOfBoundsException e) {//catch 先執行
			System.out.println("例外內容:"+e.toString());
			System.out.println("也就素超出陣列範圍");
		}finally { //此區塊一定義會被執行
			System.out.println("finally區塊執行完成");
		}
			System.out.println("執行完畢");
	}
}

```

# `11-26`

java程式語言中提供兩種方法
撰字執行緒程式
1.繼承java.lang.Thread類別
語法簡單,彈性小
2.實作Runnable介面
彈性大，解決Java單一繼承的限制

方法一
```
class MyThread extends Thread{
	MyThread(String n){
		super(n);
	}
//Thead 開始執行
public void run() {
	String tname;
	tname = super.getName();
	for(int i=1;i<=1000;i++) {
		System.out.println(tname+"("+i+")");
		}
	}
}
public class ThreadDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread t1=new MyThread("T1");
		MyThread t2=new MyThread("T2");
		t1.start();
		t2.start();

	}

}
```
```
error (???)

class MyThread extends Thread{
	MyThread(String n){
		super(n);
	}

public void run() {
	String tname;
	tname=super.getName();
	for(int i =1;i<=1000;i++) {
		System.out.println(tname+"("+i+")");
	}
}}
public class ThreadDemo {
	public static void main(String args[]) {
		MyThread t1=new MyThread("T1");
		MyThread t2=new MyThread("T2 ");
		t1.start();
		t2.start();
	}
}
```

JVM是台虛擬電腦，只安裝一顆
稱為主執行緒的cpu，可執行main()
定義的 流程
//main() Thread 

//public class TestThread

class MyThread extends Thread{
	MyThread(String n){
		super(n);
	}
public void run() {
	String tname;
	tname = super.getName();
	for(int i=1;i<=1000;i++) {
		System.out.println(tname+"("+i+")");
		}
	}
}
public class ThreadDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread t1=new MyThread("T1");
		MyThread t2=new MyThread("T2");
		t1.start();
		t2.start();

	}

}


執行緒的控制
如何暫停執行緒
讓閒置的已久或重要的執行緒先執行
sleep (time)讓自身暫停一段時間
join()可指名要哪一個執行緒join()進來
使用join()方法會暫停目前正在執行的執行緒
yield()將自身執行緒先暫停，讓其他執行緒先執行
禮讓那些在Runnable pool中的執行緒
sleep()和join()方法會拋出例外，所以要在try中呼叫
Sleep ()是非可執行狀態(主要降低自己的priority)
yield()是可執行狀態  

```
class ThreadB extends Thread{
	String str;
	int m;
	ThreadB(String a,int n){
		str = a ;//指定的字串
		m=n;//指定的間格時間
	}
	public void run() {
		try {
			for (int i=0;i<str.length();i++)
			{
				System.out.println(str.charAt(i));
				sleep(m);//暫停執行緒
			}
			}catch(InterruptedException e) {
				System.out.println("發生例外");}}}

public class Talk1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1="HELLO WORLD";
		String str2="javase10";
		Thread obt1=new ThreadB(str1,200);
		Thread obt2=new ThreadB(str2,500);
		obt1.start();
		obt2.start();

	}

}
 ```
 
```
 
class Drive implements Runnable{
	public void run() {
		System.out.println("小明到停車場");
		System.out.println("小明的愛車在停車塔內");
		Thread machine=new Thread(new Power());
		machine.start();
		try {
			machine.join();
		}catch(InterruptedException e) {
			System.out.println("小明放棄取車");
		}
			System.out.println("小明開車離開了");
	}
}
class Power implements Runnable{
	public void run() {
		System.out.println("機械開始運轉");
	try {
		for(int i=1;i<=5;i++) {
			System.out.println(i+"分鐘");}
			System.out.println();
	}catch(InterruptedException e) {
		System.out.println("機械故障");
	}
	System.out.println("愛車已經到達出口了");
	}
}
public class KKKK {
	public static void main(String[] args) {
		Thread w=new Thread(new Drive());
		w.start();
	}
}
```

# '12-1'

```
class Company{
	static int sum=0;
	synchronized static void add(int n) {
		int tmp=sum;
		tmp+=n;
	try {
		Thread.sleep(1000);
	}catch(InterruptedException e) {
		System.out.println(e.getMessage());  
	}
		sum=tmp;
		System.out.println("目前執行緒為:"+Thread.currentThread().getName()+",存款金額為"+sum);  
	  
	}
}
class Ccompany extends Thread{
	Ccompany(String str){
		super(str);
	}
	public void run() {
		for(int i=1;i<=100;i++) 
		//存100到add()
		Company.add(100);
	}
}
public class kkk {
	public static void main(String args[]) {
		Ccompany c1=new Ccompany("John");
		Ccompany c2=new Ccompany("Mary");
		c1.start();
		c2.start();
	}
}

```
```

class GoldClass implements Runnable{
	int gra;
	static int totalgra=200000000;//金塊總數
	Thread t;
	GoldClass(String name){
		gra=0;
		t=new Thread(this,name);
		t.start();//啟動執行緒
	}
	public void run(){
		while(graGold()==true){//判斷金塊是否有剩
			gra++;
		}
		System.out.println(t.getName()+"總共偷盜"+gra+"金塊");}
		synchronized static boolean graGold() { //synchronized的方法都要加在 static
			if(totalgra>0) {
				totalgra--;
				return true;
			}else {
				return false;
			}
		}
	}
	
public class kk {
	public static void main(String[] args) {
		System.out.println("總共有"+GoldClass.totalgra+"金塊");
		GoldClass g1=new GoldClass("張3");
		GoldClass g2=new GoldClass("李4");
		GoldClass g3=new GoldClass("王5");
	}
}


```
class Eating implements Runnable{
	public void run() {
		System.out.println("小明放學回家了");
		System.out.println("媽媽還沒煮晚餐");
		Thread mom=new Thread(new Cooking());
		mom.start();
		try {
			mom.join();			
		}catch (InterruptedException e) {
		System.out.println("小名開始吃晚餐");
	}
	}
}
class Cooking implements Runnable{
	public void run() {
		System.out.println("媽媽開始煮晚餐");
		try {
			for (int i=1;i<=15;i++) {
				Thread.sleep(100);
				System.out.println(i+"分鐘");}
			}catch (InterruptedException e) {
				System.out.println("媽媽罷工");
			}
		System.out.println("媽媽香噴噴的晚餐完成了");
	}
}
public class JoinDemo {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread j=new Thread (new Eating());
		j.start();
	}
 }
//題目
//小明放學回家
//媽媽還沒有煮晚餐
//媽媽開始煮晚餐
//1.2.3~15分鐘
//15分後媽媽晚餐煮好了
//小明開始吃晚餐


```

class Eating implements Runnable{
	public void run() {
		System.out.println("小名放學回家");
		System.out.println("嬤嬤還沒開始煮晚餐");
		Thread mom=new Thread(new Cooking());
		mom.start();
		try {
			mom.join();
		}catch(Exception e) {
			System.out.println("小明開始吃晚餐");
	}
}}
class Cooking implements Runnable{
	public void run(){
		System.out.println("");
		try {
			for(int i=1;i<=15;i++) 
				//存100到add()
				System.out.println(i);
		}catch(Exception e) {
			
		}System.out.println("媽媽香噴噴的晚餐做完");
	}
	
}
public class ccc {
	public static void main(String[] args) {
		Thread j=new Thread(new Eating());
		j.start();
	}
}

//用JOIN 嬤嬤的那個完成
```
```

//File 類別
java file 類別不會自己建立檔案

import java.io.*;
public class FileDown {
	public static void main(String[] args) {
		File f=new File("Note11111110");
		System.out.println(f.exists());//檢查本案是否存在
		if(!f.exists()) {
			System.out.println("利用確定成功");
		try{
			f.createNewFile();//建立檔案
		}catch(IOException e) {
			System.out.println("建立失敗"+e.toString());
		}
			System.out.println("檔案是否存在:"+f.exists());
		}
	}
}

//跟io扯上關西都要放在try catch裡面
```

//使用FileWriter 將資料寫入檔案

import java.io.*;
public class FileWriterDemo {

	public static void main(String args[]) throws IOException {
		// TODO Auto-generated method stub
		FileWriter fi=new FileWriter("Note.txt");
		//當前資料夾直接寫檔名，不是要寫C:\\資料夾\\檔案
		char data[]= {'H','E','L','L','O',',','J','A','V','A','!','\r','\n'};
		String str ="End of file";
		fi.write(data);//字入
		fi.write(str);//字入
		fi.close();
		char d[]=new char[128];
		FileReader fr =new FileReader("Note.txt");
		int num=fr.read(d);
		String s = new String (d,0,num);
		System.out.println(s);
		fr.close();
	}

}

```
import java.io.*;

public class PictDemo {
	public static void main(String[] args)throws IOException {
		FileInputStream fi=new FileInputStream("lena.gif");
		FileOutputStream fo=new FileOutputStream("lena_copy.gif");
		System.out.println("檔案大小:"+fi.available());
		byte data[]=new byte[fi.available()];
		fi.read(data);
		fo.write(data);
		fi.close();
		fo.close();
	}
}
```

```
import java.io.*;
public class aaaa {
	public static void main(String[] args) throws IOException {
		File f=new File("Note11111110");
		System.out.println(f.exists());//檢查本案是否存在
		if(!f.exists()) {
			System.out.println("利用確定成功");
		try{
			f.createNewFile();//建立檔案
		}catch(IOException e) {
			System.out.println("建立失敗"+e.toString());
		}
			System.out.println("檔案是否存在:"+f.exists());
		}
		FileWriter fi=new FileWriter("Note.txt");
		char data[]= {'H','E','L','R',',','K','T','\r','\n'};
		String str="End of file";
		fi.write(data);
		fi.write(str);
		fi.close();
		char d[]=new char[128];
		FileReader fr =new FileReader("Note.txt");
		int num=fr.read(d);
		String s=new String(d,0,num);
		System.out.println(s);
	}
}
```
```

class Eating implements Runnable{
	public void run() {
		System.out.println("小名放學回家");
		System.out.println("嬤嬤還沒開始煮晚餐");
		Thread mom=new Thread(new Cooking());
		mom.start();
		try {
			mom.join();
		}catch(Exception e) {
			System.out.println("小明開始吃晚餐");
	}
}}
class Cooking implements Runnable{
	public void run(){
		System.out.println("");
		try {
			for(int i=1;i<=15;i++) 
				//存100到add()
				System.out.println(i);
		}catch(Exception e) {
			
		}System.out.println("媽媽香噴噴的晚餐做完");
	}
	
}
public class ccc {
	public static void main(String[] args) {
		Thread j=new Thread(new Eating());
		j.start();
	}
}


```

```
import java.io.*;
public class FileDown {
	public static void main(String[] args) {
		File f=new File("Note11111110");
		System.out.println(f.exists());//檢查本案是否存在
		if(!f.exists()) {
			System.out.println("利用確定成功");
		try{
			f.createNewFile();//建立檔案
		}catch(IOException e) {
			System.out.println("建立失敗"+e.toString());
		}
			System.out.println("檔案是否存在:"+f.exists());
		}
	}
}

//跟io扯上關西都要放在try catch裡面
```

# '12-3'
//視窗介面AWT
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class AWTDemo {
	static Frame frm =new Frame("Frame");
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		frm.setSize(200,150);
		frm.setLocation(100,50);
		frm.setVisible(true);//設定視窗為可視
		frm.addWindowListener(new WindowAdapter() {//關閉視窗
			public void windowClosing (WindowEvent e) {
				System.exit(0);
			}
		});

	}
```
    
import java.awt.*;
import java.awt.event.*;
public class AWTDemo {
	static Frame frm=new Frame("Frame");
	public static void main(String[] args) {
		frm.setSize(200,150);
		frm.setLocation(100,50);
		frm.setVisible(true);
		frm.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				System.exit(0);}})	
	;
}
}
    
```

```
import java.awt.*;
import java.awt.event.*;

public class FrameDemo extends Frame implements ActionListener{
	static FrameDemo frm=new FrameDemo(); 
	static Button btn1=new Button("Yellow"); //button上的字
	static Button btn2=new Button("Green");
	static Button btn3=new Button("Exit");
			
	public static void main(String[] args) {
		btn1.addActionListener(frm); //事件傾聽者frm向btn註冊
		btn2.addActionListener(frm);
		btn3.addActionListener(frm);
		frm.setTitle("");
		frm.setLayout(new FlowLayout(FlowLayout.CENTER));
		frm.setSize(200,150);
		frm.add(btn1); //把視窗放進元件
		frm.add(btn2);
		frm.add(btn3);
		frm.setVisible(true);
	}

	@Override //actionListener的方法
	public void actionPerformed(ActionEvent e) { //我有一個事件叫e
		Button btn=(Button)e.getSource(); //事件來源 轉型  原來是ActionEvent 轉乘Button
		if(btn==btn1)
			frm.setBackground(Color.yellow);
		else if(btn==btn2)
			frm.setBackground(Color.green);
		else
			System.exit(0);
		
	}
}

```
//老師補充
import java.awt.*;
import java.awt.event.*;
public class test{
  static Frame f=new Frame("my first awt");
  static Panel p=new Panel(new GridLayout(3,3));
  static Label l=new Label("0.",Label.RIGHT);
     public static void main(String args[]){
        f.setSize(200,150);
        f.setLayout(null);
        f.setLocation(250,250);
        l.setBounds(20,30,120,20);
        p.setBounds(20,60,120,80);
          for(int i=1;i<=9;i++)
           p.add(new Button(Integer.toString(i)));
        f.add(l);
        f.add(p);
        f.setVisible(true);
  
     f.addWindowListener(new WindowAdapter(){
       public void windowClosing(WindowEvent e){System.exit(0);}});
   }
} 


import java.awt.*;
import java.awt.event.*;

public class MenuDemo extends Frame implements ActionListener{
	static MenuDemo frm =new MenuDemo();
	static Label lab =new Label("Hello",Label.CENTER);
	static MenuBar mb = new MenuBar();
	static Menu mu1 =new Menu("Style");
	static Menu mu2 =new Menu("Exit");
	static MenuItem mi1 =new MenuItem("Plain");
	static MenuItem mi2 =new MenuItem("粗體");
	static MenuItem mi3 =new MenuItem("斜體");
	static MenuItem mi4 =new MenuItem("關閉視窗");
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		frm.setTitle("記事本");
		frm.add(lab);
		
		mi1.addActionListener(frm);
		mi2.addActionListener(frm);
		mi3.addActionListener(frm);
		mi4.addActionListener(frm);
		lab.setFont(new Font("Dialog",Font.PLAIN,24));
		frm.setMenuBar(mb);
		frm.setSize(200,150);
		frm.setVisible(true);
		mb.add(mu1);
		mb.add(mu2);
		mu1.add(mi1);
		mu1.add(mi2);
		mu1.add(mi3);
		mu2.add(mi4);
		frm.add(lab);
		frm.addWindowListener(new WindowAdapter() {//關閉視窗
			public void windowClosing (WindowEvent e) {
				System.exit(0);
			}
		});
	}
	public void actionPerformed(ActionEvent e) {
		MenuItem mi = (MenuItem)e.getSource();
		if (mi==mi1)
			lab.setFont(new Font("Dialog",Font.PLAIN,24));
		else if (mi==mi2)
			lab.setFont(new Font("Dialog",Font.BOLD,24));
		else if (mi==mi3)
			lab.setFont(new Font("Dialog",Font.ITALIC,24));
		else
			frm.dispose();
		
	}

}
```

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyJFrame extends JFrame{	
	private JPanel contentPane;
	String[] imgName=new String[]{"水母","企鵝","無尾熊"};
	JButton btnPrev,btnNext;
	JLabel lblName,lblImg,lblShow;
	int n=0;
	//建構子
	MyJFrame(){
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100,100,230,310);
		contentPane=new JPanel();
		setContentPane(contentPane);
		contentPane.setLayout(null);
		lblImg=new JLabel();
		lblImg.setIcon(new ImageIcon(""+imgName[n]+".jpg"));
		lblImg.setBounds(20, 30, 180, 235);
		contentPane.add(lblImg);
		lblName=new JLabel(imgName[n]);
		lblImg.setBounds(20, 75, 180, 25);
		contentPane.add(lblImg);
		String show="第"+(n+1)+"張,共"+imgName.length+"張";
		lblShow=new JLabel(show);
		lblShow.setBounds(20,200,180,25);
		contentPane.add(lblShow);
		
		btnPrev = new JButton("上一張");
		btnPrev.setBounds(20, 230, 80, 25);
		contentPane.add(btnPrev);
		btnPrev.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				n--;
				if (n < 0) {
					n = imgName.length - 1;
				}
				lblImg.setIcon(new ImageIcon("" + imgName[n] + ".jpg"));
				lblName.setText(imgName[n]);
				lblShow.setText("第" + (n + 1) + "張,共" + imgName.length + "張");
			}
		});

		btnNext = new JButton("下一張");
		btnNext.setBounds(120, 230, 80, 25);
		contentPane.add(btnNext);
		btnNext.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				n++;
				if (n >= imgName.length) {
					n = 0;
				}
				lblImg.setIcon(new ImageIcon("" + imgName[n] + ".jpg"));
				lblName.setText(imgName[n]);
				lblShow.setText("第" + (n + 1) + "張,共" + imgName.length + "張");
			}
		});

		
		setVisible(true);}}

public class AnimalDemo{
	public static void main(String[] args) {
		MyJFrame f=new MyJFrame();
	}
}

		
```
```

import java.awt.*;
import java.awt.event.*;

public class FrameDemo extends Frame implements ActionListener{
	static FrameDemo frm=new FrameDemo(); 
	static Button btn1=new Button("Yellow"); //button上的字
	static Button btn2=new Button("Green");
	static Button btn3=new Button("Exit");
			
	public static void main(String[] args) {
		btn1.addActionListener(frm); //事件傾聽者frm向btn註冊
		btn2.addActionListener(frm);
		btn3.addActionListener(frm);
		frm.setTitle("");
		frm.setLayout(new FlowLayout(FlowLayout.CENTER));
		frm.setSize(200,150);
		frm.add(btn1); //把視窗放進元件
		frm.add(btn2);
		frm.add(btn3);
		frm.setVisible(true);
	}

	@Override //actionListener的方法
	public void actionPerformed(ActionEvent e) { //我有一個事件叫e
		Button btn=(Button)e.getSource(); //事件來源 轉型  原來是ActionEvent 轉乘Button
		if(btn==btn1)
			frm.setBackground(Color.yellow);
		else if(btn==btn2)
			frm.setBackground(Color.green);
		else
			System.exit(0);
		
	}
}

```
# '12-8'
簡報執行檔
Set 介面
public interface 
Set 中置放的元素是無順序性，並且元素和元素不得重複

資料室唯一但無順序性的集合
    Abstract > HashSet
Set 
    SortedSet >TreeSet
    
HashSet

public class HashSet implements extends AbstractSet implements Set 

元素內容沒有順序性不能重複


import java.util.*;


public class SetDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Set word = new HashSet();
		Scanner s = new Scanner(System.in);
		System.out.println("請輸入英文:");
		String line = s.nextLine();
		String []tokens =line.split(" ");
		for (String token :tokens)
			word.add(token);
		System.out.printf("不重複的單字有%d個,%s%n",word.size(),word);
			
	
	}

}

```
import java.util.*;
public class App01 {
	public static void main(String[] args) {
		Set word=new HashSet();
		Scanner s=new Scanner(System.in);
		System.out.println("請輸入英文");
		String line =s.nextLine();
		String[] tokens=line.split(" ");
		for(String token:tokens)
			word.add(token);
			System.out.printf("不得重複單字有%d個,%s%n",word.size(),word);
	}
	
}
```
//利用Iterator 將HashSet中所有的元素依序取出
import java.util.*;
public class HashSetDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashSet hs =new HashSet();
		//將元素加入
		hs.add("Vincent Tuan");
		hs.add("Anita Wu");
		hs.add("Howard Tuan");
		//加入null
		hs.add(null);
		System.out.println("直接列印元素:"+hs);
		System.out.println("透過Iterator取出後列印");
		Iterator i =hs.iterator();
		while (i.hasNext())
			System.out.print(i.next());
	}

}

```
//利用Iterator將HashSet中所有的元素依序取出
import java.util.*;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetDemo {
	public static void main(String[] args) {
		HashSet hs=new HashSet();
		//將元素加入
		hs.add("Vincent Tuan");
		hs.add("Anita Wu");
		hs.add("Howard Tuan");
		//加入null
		hs.add(null);
		System.out.println("直接列印元素"+hs);
		System.out.println("透過Iterator取出後 列印");
		Iterator i=hs.iterator();
		while(i.hasNext())
			System.out.println(i.next());	
	}
}

```

```

```
//Java 9 之後新增
List.of(),Set.of(),Mop.of()
未建立不可變集合(immutable Collect)
import java.util.*;
//Java 9 之後新增
//List.of(),Set.of(),Mop.of()
//未建立不可變集合(immutable Collect)
public class ImmutableDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		var hset = new HashSet<>();
		hset.add("白虎");
		var charAnimal=Set.of("青龍","白虎","朱雀","玄武");
		for (String p:charAnimal)
			hset.add(p);
		String myAui="虎";
		hset.add(myAui);
		System.out.println(hset);
	}
}

SortedSet
public class SortedSet exterds Set
其內容為自然排序,不可重複
TreeSet
public class TreeSet extends AbstractSet
也是自然排序,其應用在搜尋機制上會比Array或List 快得多


import java.util.*;
public class TreeSetDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SortedSet s=new TreeSet();
		s.add("1");
		s.add("Anita");
		s.add("Vincent");
		s.add("Z");
		System.out.println("原始的SortedSet元素資料");
		System.out.println(s);

	}
}


API:
https://docs.oracle.com/javase/9/docs/api/overview-summary.html

import java.util.*;
public class TreeSetClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//var tset = new TreeSet();
		TreeSet<Integer> tset = new TreeSet<>();
		var number = Set.of(23,45,9,-6,8,18,93,100,76,54,66,89,34,0,-55,-27,61);
		for (int n:number)
			tset.add(n);
		System.out.println("物件元素的內容");
		System.out.println(" "+tset);
		System.out.println("第一個元素內容:"+tset.first());
		System.out.println("最後一個元素內容:"+tset.last());
		Scanner Keyin =new Scanner(System.in);
		int num=0;
		while(true) {
			System.out.println("請輸入一個整數:");
			try {
				num=Integer.parseInt(Keyin.nextLine());
			}catch (NumberFormatException e) {
				System.out.println("請輸入數值");
				continue;}
			if (num>=(int)tset.first()&&num<=(int)tset.last())
				break;
			else
				System.out.println("範圍錯誤");}
		System.out.println("元素內容大於等於"+num+"者");
		System.out.println(tset.tailSet(num));
			
			}		
	}


```

import java.util.Set;
import java.util.TreeSet;
import java.util.*;

public class TreeSetClass {
	public static void main(String[] args) {
		//var tset =new TreeSet(); 可以用這兩個方式宣告 泛型
		TreeSet<Integer> tset=new TreeSet();
		var number=Set.of(23,45,9,-6,8,18,93,100,76,54,66,89,34,0,-55,-27,61);
		for(int n:number)
			tset.add(n);
			System.out.println("物件元素的內容");
			System.out.println(tset);
			System.out.println("第一個元素內容:"+tset.first()+"最後一個元素內容"+tset.last());
			
			Scanner keyin=new Scanner(System.in);
			int num=0;
			while(true) {
				System.out.println("請輸入一個整數");
				try {
					num=Integer.parseInt(keyin.nextLine());
				}catch(NumberFormatException e) {
					System.out.println("物件元素的內容");
					continue; //他會再回到while 迴圈
				}
				if(num>=(int)tset.first()&&num<=(int)tset.last())
					//System.out.printf("結束");
					break;
				else 
					System.out.println("範圍錯誤");
				System.out.println("元素內容大於等於"+num+"者");
				System.out.println(tset.tailSet(num));
			}
			//api裡面倒數第二個
	}
}
```
```
import java.util.TreeSet;
import java.util.*;
public class TreeSetDemo {
	public static void main(String[] args) {
		SortedSet s=new TreeSet();
		s.add("1");
		//s.add("");
		s.add("Anita");
		s.add("Vincent");
		s.add("Z");
		System.out.println("原始的SortSet元素資料");
		System.out.println(s);
	}
}
```

```
import java.util.HashSet;
import java.util.Set;

//Java 9之後新增
public class ImmutableDemo {
	//未建立不可變集合(immutable collection)
	public static void main(String[] args) {
		var hset =new HashSet<>(); //泛型
		hset.add("白虎");
		var charAnimal=Set.of("青龍","白虎","朱雀","玄武");
		for(String p:charAnimal)
			hset.add(p);
		String myAni="壁虎";
		hset.add(myAni);
		System.out.println(hset);
	}

}
```
# '12-10'

List 介面
List 繼承Collection介面
List 中的元素有順序姓，且資料可以重複
作用是收集物件，並以索引的方式保留
收集的物件順序
實作的類別之一是java.util.ArrayList
public interface List extends Collection

ListIterator 介面
public interface ListIterator

extends Iterator

其特色是允許上下移動


```
import java.util.ArrayList;
import java.util.ListIterator;

public class App01 {
public static void main(String[] args) {
		System.out.println("");
		ArrayList<String> alist =new ArrayList();
		String[] place={"宜蘭","花蓮","天祥","台東","知本"};
		for(String p:place)
			alist.add(p);
		System.out.println("顯示alist集合物件元素");
		System.out.println(alist);
		ListIterator<String> litera=alist.listIterator();
		System.out.println("\n修改alist集合物件元素");
		while(litera.hasNext()) {
			litera.hasNext();
			if(litera.nextIndex()==3)
				alist.set(3, "瑞穗");
		}
		System.out.println("\n反向走訪alist集合物件元素");
		while(litera.hasPrevious()) {
			System.out.print(litera.previous()+"");
			System.out.println();
			System.out.println("新增alist物件");
			litera=alist.listIterator(3);
			litera.add("池上");
			System.out.println("\n顯示alist最終元素");
			System.out.println();
		}
}
	
}
```
import java.util.ArrayList;
import java.util.ListIterator;

public class ListIteratorDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("建立alist集合物件...");
		ArrayList<String> alist= new ArrayList<>();
		String[] place= {"宜蘭","花蓮","天祥","台東","知本"};
		for (String p:place)
			alist.add(p);
		System.out.println("顯示alist集合物件元素");
		System.out.println(alist);
		ListIterator<String> litera= alist.listIterator();
		System.out.println("\n修改的list集合物件元素");
		System.out.println(alist);
		while (litera.hasNext()) {
			litera.next();
			if (litera.nextIndex()==3)
				alist.set(3,"瑞穗");	
		}
		System.out.println("\n反向走訪alist集合物件元素");
		System.out.println(alist);
		while(litera.hasPrevious())
			System.out.print(litera.previous()+"");
		System.out.println();
		System.out.println("新增alist物件");
		System.out.println(alist);
		litera=alist.listIterator(3);
		litera.add("池上");
		System.out.println("\n顯示的alist最終元素");
		System.out.println(alist);
		System.out.println();
	
	}
}
作業

import java.util.ArrayList;
import java.util.ListIterator;

public class ListIteratorHW1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("建立alist集合物件...");
		ArrayList<String> alist= new ArrayList<>();
		String[] place= {"1","2","3"};
		for (String p:place)
			alist.add(p);
		System.out.println("顯示alist集合物件元素");
		System.out.println(alist);
		ListIterator<String> litera= alist.listIterator();
		System.out.println("新增alist物件");
		litera=alist.listIterator(2);
		litera.add("100");
        //顯示{1,2,100,3}
		System.out.println(alist);
		System.out.println("\n顯示的alist最終元素");
		System.out.println(alist.get(1));
        //取得陣列[1]的數值=2
		System.out.println(alist);
		System.out.println(alist.remove(0));
        //刪除陣列[0]的數值={2,100,3}
		System.out.println(alist);
		System.out.println();
		
	
	}
}


```
import java.util.ArrayList;
import java.util.ListIterator;

public class App02 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("建立alist集合物件...");
		ArrayList<Integer> alist= new ArrayList<>();
		Integer[] place= {1,2,3};
		for (Integer p:place)
				alist.add(p);
		System.out.println("顯示alist集合物件元素");
		System.out.println(alist);
		ListIterator<Integer> litera= alist.listIterator();
		System.out.println("\n修改的list集合物件元素");
		System.out.println(alist);
		/*
		while (litera.hasNext()) {
			litera.next();
			if (litera.nextIndex()==3)
				alist.set(3,3);	
		}
		*/
		System.out.println("\n反向走訪alist集合物件元素");
		System.out.println(alist);
		while(litera.hasPrevious())
			System.out.print(litera.previous()+"");
		System.out.println();
		System.out.println("新增alist物件");
		System.out.println(alist);
		litera=alist.listIterator(2);
		litera.add(100);
		System.out.println("\n顯示的alist最終元素");
		System.out.println(alist.get(0));
		System.out.println(alist.remove(0));
		System.out.println(alist);
		
	
	}
}

```


//LinkedList
//採用(Link)連結的結構
import java.util.LinkedList;
public class LinkedListDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LinkedList<Integer>list = new LinkedList<>();
		for (int i=10;i<=30;i+=10)
			list.add(i);
		System.out.println(list);
		//將100插入在第一個位置
		list.addFirst(100);
		System.out.println(list);
		//將200插入在最後的位置
		list.addLast(200);
		System.out.println(list);
		//將300插入在第一個位置
		list.addFirst(300);
		System.out.println(list);
		//顯示部分集合內容
		for (int i=0;i<list.size();i++)
			System.out.print(list.get(i)+" ");
		System.out.println("\n刪除最後一個元素:");
		System.out.println(list.removeLast());
		System.out.println(list);
		System.out.println("第一個元素:"+list.getFirst());
		System.out.println("最後一個元素:"+list.getLast());
		System.out.println("元素值為10的索引值"+list.indexOf(10));
		System.out.println(list);
	}

```
}

import java.util.LinkedList;
import java.util.*;
import java.util.ListIterator;
import java.util.ArrayList;

public class LinkedListDemo {

	public static void main(String[] args) {
		//LinkedListedDemo<Integer> list=new LinkedListDemo<>();
		LinkedList<Integer>list = new LinkedList<>();
		for(int i=10;i<30;i+=10)
			list.add(i);
		//將100插在第一個位置
			list.addFirst(100);
		//將200插在最後一個位置
			list.addLast(200);
		//將300插在第一個位置
		//顯示集合集合
		
		for(int i=0;i<list.size();i++)
			System.out.println(list.get(i)+" ");
			System.out.println();
			System.out.println("第一個元素:"+list.getFirst());
			System.out.println("\n刪除一個元素:"+list.removeLast());
			System.out.println("最後一個元素:"+list.getLast());
			System.out.println("元素值200的索引值:"+list.indexOf(200));
	}

}

```
```

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

public class LinkedListClass {
	public static void main(String[] args) {
		var place =List.of("蘋果","水梨","香蕉","奇異果","芭樂");
		var night=new ArrayList<>();
		for(String p:place)
			night.add(p);
			System.out.println("\n串列元素前後的順序");
			for(int i=0;i<night.size();i++)
				System.out.println("第"+(i+1)+"個"+night.get(i));
			var queue=new LinkedList<>();
			System.out.println("\n取出的方式先進先出");
		for(int j=queue.size()-1;j>0;j--) {
			System.out.println(queue.getFirst()+"");
			queue.removeFirst();}
			System.out.println("");
			var stack=new LinkedList(night);
			System.out.println("\n取出的方式後進先出");
			while(true){
				System.out.print(stack.removeLast()+" ");
				if(stack.isEmpty())
					break;
			}
	}
}
```

import java.util.*;
public class LinkedListClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		var place =List.of("蘋果","水梨","香蕉","奇異果","芭樂");		
		var night =new ArrayList<>();
		for (String p:place)
			night.add(p);
		System.out.println("\n串列元素前後的順序:");
		for (int i=0;i<night.size();i++)
			System.out.println("第"+(i+1)+"個"+night.get(i));
		var queue=new LinkedList<>(night);
		System.out.println("\n取出方式:先進先出");
		for (int j =queue.size()-1;j>=0;j--) {
			System.out.print(queue.getFirst()+" ");
		queue.removeFirst();}
		System.out.println();
		var stack=new LinkedList(night);
		System.out.println("\n取出方式:後進先出");
		while(true) {
			System.out.print(stack.removeLast()+" ");
			if(stack.isEmpty())
				break;
			
		}
			

	}

}

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

public class ArrayListDemo {
	public static void main(String[] args) {
		//利用Array
		System.out.println("東部旅遊夜素規劃");
		ArrayList<String> night=new ArrayList<>();
		var place=List.of("宜蘭","花蓮","天祥","花蓮","台中");
		for(String p:place)
			night.add(p);
		System.out.println("初期夜素地點:"+night);
		System.out.println("初期夜素天數:"+night.size());
		night.add("知本");
		night.add(4,"池上");
		System.out.println("修訂後夜宿的地點"+night);
		System.out.println("夜宿天祥規劃在第幾天:"+(night.indexOf("天祥")+1));
		System.out.println("刪除\"花蓮\"第一個夜宿"+night.remove(night.indexOf("花蓮")));
	
		System.out.println("~確定夜宿表列~");
		for(int i=0;i<night.size();i++)
			System.out.println("第"+(i+1)+"天夜宿的地點:"+night.get(i));
		
	}
}
```
```

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

public class ArrayListDemo {
	public static void main(String[] args) {
		//利用Array
		System.out.println("東部旅遊夜素規劃");
		ArrayList<String> night=new ArrayList<>();
		var place=List.of("宜蘭","花蓮","天祥","花蓮","台中");
		for(String p:place)
			night.add(p);
		System.out.println("初期夜素地點:"+night);
		System.out.println("初期夜素天數:"+night.size());
		night.add("知本");
		night.add(4,"池上");
		System.out.println("修訂後夜宿的地點"+night);
		System.out.println("夜宿天祥規劃在第幾天:"+(night.indexOf("天祥")+1));
		System.out.println("刪除\"花蓮\"第一個夜宿"+night.remove(night.indexOf("花蓮")));
	
		System.out.println("~確定夜宿表列~");
		for(int i=0;i<night.size();i++)
			System.out.println("第"+(i+1)+"天夜宿的地點:"+night.get(i));
		
	}
}
```

# '12-15'
Map 介面
Map中利用指定的Key(鍵值)來決定元素擺放位置
鍵值不得重複 每一個鍵值最多只能對立一個元素
不同的鍵值可以存相同的元素
Map 並沒有extends collections

public interface Map

HashTable 和 HashMap 這兩個類別實作Map介面

跟list不一樣 一個用add 一個用put 
Map 的架構

```
import java.util.Map;
import java.util.Scanner;
import java.util.*;
public class App01 {
	public static void main(String[] args) {
		Map<String,String> message =new HashMap<>();
		//Map介面透過put進行新增
		message.put("Justin","Hello 這是justin訊息");
		message.put("Monica","Hello 這是Monica訊息");
		message.put("Mary","Hello 這是Mary訊息");
		Scanner scan=new Scanner(System.in);
		System.out.println("取得誰的訊息?");
		//Map透過get取得
		String m=message.get(scan.nextLine());
		System.out.println(m);
		System.out.println(message);
		
	}
}

```
```

//keySet,value

import java.util.HashMap;
import java.util.Map;
import java.util.*;

public class MaykeyValue {
	public static void main(String[] args) {
		Map<String,String> map =new HashMap<>();
		map.put("one","一");
		map.put("two","二");
		map.put("three","三");
		System.out.println("顯示鍵");
		foreach(map.keySet());
		System.out.println("顯示值:");
		foreach(map.values());
	}
	public static void foreach(Iterable<String> iterable) {
		for(String element:iterable) //母體集合
			System.out.println(element);
	}
}

```

課中作業

"Alex",92
"Boddy",85
"Kitty",90
"Judy",70
取"Kitty","Judy",Joice成績

import java.util.*;
public class MayKeyValueHW {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
				Map<String,String> map =new HashMap<>();
				map.put("Alex","92");
				map.put("Boddy","85");
				map.put("Kitty","90");
				map.put("Judy","70");
				Scanner scan=new Scanner (System.in);
				System.out.println("取得誰的成績?");
				String m = map.get(scan.nextLine());
				System.out.println(m);


	}

}

```
import java.util.*;
public class HashMapDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//var map = new HashMap<>();
		HashMap<String,String>hmap=new HashMap<>();
		hmap.put("張三谷", "牧師");
		var post=Map.of("何九山","教師","李四斐","警察","周六圖","教師");
		hmap.putAll(post);
		System.out.println("集合內容"+hmap);
		System.out.println("集合元素個數:"+(hmap.size()+1));
		System.out.println("\n加入\"何九山\"");
		if (hmap.containsKey("何九山"))
			System.out.println("\"何九山\" 已經存在,重複加入會被覆蓋");
		hmap.put("何九山", "軍人");
		System.out.println("何九山職業更名為:"+hmap.get("何九山"));
		System.out.println("\n加入\"曹五操\"");
		String name="曹五操";
		if(hmap.containsKey(name))
			System.out.println(name+"\"已經存在\"不接受更改");
		else
			hmap.put(name,"律師");
		System.out.println("移除\"周六圖\"");
		hmap.remove("周六圖");
		System.out.println("集合內容2"+hmap);
		
	}

}
`

```
import java.util.HashMap;
import java.util.Map;
import java.util.*;
import java.util.Scanner;

public class App03
{
	public static void main(String[] args) {
		//var map=new HashMap<>();
		Map<String,String> hmap =new HashMap<>();
		
		hmap.put("張三谷", "牧師");
		var post=Map.of("何九三", "教師","李四非","警察","周六國","教師");//只要適用of 的東西都不能修改
		hmap.putAll(post); //把所有的東西放進去
		System.out.println("集合內容:"+hmap);
		System.out.println("集合個數:"+hmap.size());
		//System.out.println("\n加入\"何九山\"");
		if(hmap.containsKey("何九三"))  //透過containsKey加入何九山
			System.out.println("\"何九山\"已經存在再重複加入會被覆蓋");
		hmap.put("何九三", "軍人");
		System.out.println("何九山的職業更名為:"+hmap.get("何九三"));
		System.out.println("\n加入\"曹五操\"");
		String name="曹五操";
		if(hmap.containsKey(name))
			System.out.println(name+"\"已經存在\"不接受更改");
		else 
			hmap.put(name,"律師");
		System.out.println("移除\"周六國\"...");
		hmap.remove("周六國");
		Scanner scan=new Scanner(System.in);
		//String m=hmap.get(scan.nextLine());	
		String s1=scan.nextLine();	
		String s2=scan.nextLine();	
		hmap.put(s1,s2);
		System.out.println("集合內容為:"+hmap);
	}
}	


HashMap,TreeMap
是否允許null
HashMap接受TreeMap不接受
HashMap依照自己的定義進行排序
若要正常排序，可以選擇TreeMap但效能較差

import java.util.*;
public class TreeMapDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//var tmap = new TreeMap<>();
		TreeMap<Integer,String>tmap = new TreeMap<>();
		tmap.put(260,"宜蘭");
		tmap.put(970,"花蓮");
		tmap.put(500,"彰化");
		tmap.put(900,"屏東");
		tmap.put(600,"嘉義");
		System.out.println("集合內容:"+tmap);
		System.out.println("集合內容個數:"+tmap.size());
		int key=(int)tmap.firstKey();
		System.out.println("第一個郵遞區號:"+key);
		System.out.println("第一個地名:"+tmap.get(key));
		int lkey=(int)tmap.lastKey();
		System.out.println("最後一個郵遞區號:"+lkey);
		System.out.println("最後一個地名:"+tmap.get(lkey));
		System.out.println("郵遞區號大於等於:"+600+"的集合元素:"+tmap.tailMap(600));

	}

}



12-29號喔喔喔喔

```
import java.util.TreeMap;

public class TreeMapDemo {
	public static void main(String[] args) {
		TreeMap<Integer,String> tmap=new TreeMap<>();
		tmap.put(260,"宜蘭");
		tmap.put(970,"花蓮");
		tmap.put(500,"彰化");
		tmap.put(900,"屏東");
		tmap.put(600,"嘉義");
		System.out.println("集合內容:"+tmap);
		System.out.println("集合元素個數:"+tmap.size());
		int key=(int)tmap.firstKey();
		System.out.println("第一個郵遞區號"+key);
		System.out.println("第一個地名"+tmap.get(key));
		int key1=(int)+tmap.lastKey();
		System.out.println("最後一個郵遞區號"+key1);
		System.out.println("最後一個地名"+tmap.get(key1));
		System.out.println("郵遞區號大於等於"+600+"的集合"+tmap.tailMap(600));
	}
}
```
```

//public String substring(int beginIndex,int endIndex) //結束減1
//"uppengaraden.com"
// 0123456789
public class SubStringDemo {
	public static void main(String[] args) {
		String str=new String("uppengaraden.com");
		System.out.println(str.substring(4));
		System.out.println("返回值2:");
		System.out.println(str.substring(4,10));
		System.out.println("返回值3");
		System.out.println("uppengaraden.com".substring(4,10));
		StringBuilder s=new StringBuilder("123456789");
		StringBuilder s1=s.replace(2,4,"Java");
		System.out.println(s1);
	}
}


```

//String
//public String substring(int beginIndex,int endIndex)

public class SubStringDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str = new String("uppengarden.com");
		System.out.println("返回值1:");
		System.out.println(str.substring(4));
		System.out.println("返回值2:");
		System.out.println(str.substring(4,10));
		System.out.println("返回值3:");
		System.out.println("uppengarden.com".substring(4,10));
		StringBuilder s =new StringBuilder("123456789");
		//StringBuilder s1=s.replace(2, 4, "JAVA");
		s=s.replace(2, 4, "JAVA");//可寫上面的方式也可以寫這樣
		System.out.println(s);
		
		

	}

}

```
# '12-17'
//版面配置
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;

class InterFrame extends JFrame implements ActionListener{
	private static final String String = null;
	private Border lineB = BorderFactory.createLineBorder(Color.blue);
	private JRadioButton[] rdb = new JRadioButton[2];
	private JCheckBox[] chk = new JCheckBox[3];
	private JLabel lblShow = new JLabel("請選擇性別,興趣...");
	InterFrame(){
		setTitle("興趣調查表");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(50,50,250,240);
		setLayout(null);
		JPanel panSex =new JPanel();
		add(panSex);
		panSex.setBounds(30,20,80,120);
		panSex.setBorder(BorderFactory.createTitledBorder(lineB,"性別"));
		panSex.setLayout(new FlowLayout(FlowLayout.LEFT));
		ButtonGroup group =new ButtonGroup();
		rdb[0]=new JRadioButton("男",true);
		rdb[1]=new JRadioButton("女",true);
		for (int i=0;i<rdb.length;i++) {
			group.add(rdb[i]);
			panSex.add(rdb[i]);
			rdb[i].addActionListener(this);
		}
	JPanel panInter = new JPanel();
	add (panInter);
	panInter.setBounds(130,20,80,120);
	panInter.setBorder(BorderFactory.createTitledBorder(lineB,"興趣"));
	panInter.setLayout(new FlowLayout(FlowLayout.LEFT));
	chk[0]=new JCheckBox("音樂");
	chk[1]=new JCheckBox("美術");
	chk[2]=new JCheckBox("表演");
	for (int i=0;i<chk.length;i++) {
		panInter.add(chk[i]);
		chk[i].addActionListener(this);}
	add(lblShow);
	lblShow.setBounds(20,160,200,30);
	lblShow.setBorder(lineB);
	setVisible(true);
	}
	public void actionPerformed(ActionEvent e) {
		String stShow =" ";
		if (rdb [0].isSelected())
			stShow += "先生，你";
		else 
			stShow += "小姐，妳";
		
		if (!(chk[0].isSelected()||chk[1].isSelected()||chk[2].isSelected()))
			stShow+="是個無聊的人";
		else {
			String inter = " ";
				if (chk[0].isSelected())
					inter += chk[0].getText()+" ";
				if (chk[1].isSelected())
					inter += chk[1].getText()+" ";
				if (chk[2].isSelected())
					inter += chk[2].getText()+" ";
				stShow += "的興趣是"+inter;
				}
	
    lblShow.setT
    ext(stShow);
	}
}
```
```
public class Interest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new InterFrame();
	}
}
```

```
public void createTable() {
		try {
			stat=con.createStatement();
			stat.executeUpdate(createdbSQL);
		}catch(SQLException e) {
			System.out.println("CreateTable Exception:"+e.toString());
		}finally {
			Close();
		}
	}
    

<<<<<SQL>>>>>


import java.sql.*;
public class jdbcmysql {
	private Connection con=null;
	private Statement stat =null;
	private ResultSet rs=null;
	private PreparedStatement pst=null;
	private String dropdbSQL="DROP TABLE User";
	
	private String createdbSQL = "CREATE TABLE User (" + 
            "    id     INTEGER " +
		    "  , name    VARCHAR(20) " + 
            "  , passwd  VARCHAR(20))";
			
	private String insertdbSQL = "insert into User(id,name,passwd) " + "select ifNULL(max(id),0)+1,?,? FROM User";
	private String selectSQL="select *from User";
	
	public jdbcmysql() {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			con=DriverManager.getConnection("jdbc:mysql://localhost/test?serverTimezone=UTC&useUnicode=true&characterEncoding=Big5&useSSL=false", "root","12345678");
		}catch(ClassNotFoundException e) {
			System.out.println("DriverClassNotFound :"+e.toString());
		}catch(SQLException x) {
			System.out.println("Exception :"+x.toString());
		}
	}
	
	public void dropTable() {
		try {
			stat=con.createStatement();
			stat.executeUpdate(dropdbSQL);
		}catch(SQLException e) {
			System.out.println("Drop DB Exception");
		}finally {
			Close();
		}
	}
	public void SelectTable() {
		try {
			stat=con.createStatement();
			rs=stat.executeQuery(selectSQL);
			System.out.println("ID\t\t Name\t\t PASSWORD");
			while(rs.next()) {
				System.out.println(rs.getInt("Id")+"\t\t"+rs.getString("name")+"\t\t"+rs.getString("passwd"));
			}
		}catch(SQLException e) {
			System.out.println("SelectTable Exception:"+e.toString());
		}finally {
			Close();
		}
	}
	public void createTable() {
		try {
			stat=con.createStatement();
			stat.executeUpdate(createdbSQL);
		}catch(SQLException e) {
			System.out.println("CreateTable Exception:"+e.toString());
		}finally {
			Close();
		}
	}
	public void insertTable(String name ,String passwd) {
		try {
			pst=con.prepareStatement(insertdbSQL);
			pst.setString(1,name);
			pst.setString(2,passwd);
			pst.executeUpdate();
			
		}catch(SQLException e) {
			System.out.println("InsertTable Exception:"+e.toString());
		}finally {
			Close();
		}
	}
	private void Close() {
		try {
			if(rs!=null) {
				rs.close();
			    rs=null;
			}
			if(stat!=null) {
				stat.close();
				stat=null;
			}
			if(pst!=null) {
				pst.close();
				pst=null;
			}
		}catch(SQLException e) {
			System.out.println("Exception:"+e.toString());
		}
	}
	

	public static void main(String[] args) {
		jdbcmysql t=new jdbcmysql();
		t.dropTable();
		t.createTable();
		t.insertTable("Mary", "123456");
		t.insertTable("kim", "899");
		t.SelectTable();
		
		
	}

}
```

```

# 12-22

```
Delete 

public void delete(String username, String password) {
		
		String sql="DELETE FROM USER WHERE username='"+username+"' AND password='"+password+"'";

		try {
			int a=statement.executeUpdate(sql);
			con.close();
			statement.close();
			if(a==1) {
				JOptionPane.showMessageDialog(null,"刪除成功");
			}
		}catch(SQLException e) {
			JOptionPane.showMessageDialog(null,"刪除有誤");
			e.printStackTrace();
		}
		
	}
```

import java.sql.*;

import javax.swing.JOptionPane;
public class Jdbcs {
	Connection con=null;
	Statement statement=null;
	ResultSet res=null;	
	String driver="com.mysql.cj.jdbc.Driver";
	String url="jdbc:mysql://localhost/user?serverTimezone=UTC&useUnicode=true&characterEncoding=Big5&useSSL=false";
	String name="root";
	String passwd="12345678";

	public Jdbcs() {
		try {
			Class.forName(driver).newInstance();
			con=DriverManager.getConnection(url,name,passwd);
			statement=con.createStatement();
		}catch(ClassNotFoundException e) {
			System.out.println("對不起找不到這個Driver");
			e.printStackTrace();
		}catch(SQLException e) {
			e.printStackTrace();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	//用戶註冊
	public void insert(String username,String password) {
		if(username==null ||username.trim().length()<=0) {
			JOptionPane.showMessageDialog(null, "帳號為空 請重新註冊!");
			return;
		}
		String sql="insert into user(username,password)value(\""+username+"\",\""+password+"\")";
		try {
			int a=statement.executeUpdate(sql);
			con.close();
			statement.close();
			if(a==1) {
				JOptionPane.showMessageDialog(null,"註冊成功");
			}
		}catch(SQLException e) {
			JOptionPane.showMessageDialog(null,"該用戶已經有了!");
			e.printStackTrace();
		}
	}


	public boolean compare(String username, String password) {
		boolean m=false;
		String sql="select password from user where username=\""+username+"\"";
		try {
			res=statement.executeQuery(sql);
			if(res.next()) {
				String pa=res.getString(1);
				System.out.println(pa+" "+password);
				if(pa.equals(password)) {
					m=true;
				}else {
					JOptionPane.showMessageDialog(null,"密碼錯誤");
				}
			}else {
				JOptionPane.showMessageDialog(null,"用戶不存在!");
			}
			res.close();
			con.close();
			statement.close();
		}catch(SQLException e) {
			e.printStackTrace();
	}
		return m;
	}


	public boolean update(String username, String password1, String newpassword) {
		String sql="UPDATE FROM USER WHERE username='"+username+"' AND password='"+password+"'";

		try {
			int a=statement.executeUpdate(sql);
			con.close();
			statement.close();
			if(a==1) {
				JOptionPane.showMessageDialog(null,"刪除成功");
			}
		}catch(SQLException e) {
			JOptionPane.showMessageDialog(null,"刪除有誤");
			e.printStackTrace();
		}
		
	}
	}

	public void delete(String username, String password) {
		if(compare(username,password)) {
			JOptionPane.showMessageDialog(null,"已經完成刪除");
		}else {
			return;
		}
		
		try {
			con=DriverManager.getConnection(url,name,passwd)
			String sql="DELETE FROM USER WHERE username='"+username+"'";
			statement.executeUpdate(sql);
			int a=statement.executeUpdate(sql);
			
		}catch(SQLException e) {
			JOptionPane.showMessageDialog(null,"刪除有誤");
			e.printStackTrace();
		}
		
	}
}

```
```

<<<Jdbcs>>>
這是一個連結資料庫可以登入註冊刪除帳號修改密碼的專案


```
import java.sql.*;

import javax.swing.JOptionPane;
public class Jdbcs {
		Connection con =null;
		Statement statement =null;
		ResultSet res = null;
		String driver ="com.mysql.cj.jdbc.Driver";
		String url = "jdbc:mysql://localhost/user?serverTimezone=UTC&useUnicode=true&characterEncoding=Big5&useSSL=false";
		String name ="root"; 
		String passwd ="12345678"; 
		public Jdbcs() {
			try {
				Class.forName(driver).newInstance();
				con=DriverManager.getConnection(url,name,passwd);
				statement = con.createStatement();
			}catch (ClassNotFoundException e ) {
				System.out.println("對不起!找不到這個Deiver");
				e.printStackTrace();
			}catch (SQLException e) {
				e.printStackTrace();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
//用戶註冊
		public void insert(String username,String password) {
			if (username == null|| username.trim().length()<=0) {
				JOptionPane.showMessageDialog(null, "註冊帳號為空，請重新註冊");
				return;
			}
			String sql = "insert into user(username,password)values(\""+username+"\",\""+password+"\")";
			try {
				int a = statement.executeUpdate(sql);
				con.close();
				statement.close();
				if (a==1) {
					JOptionPane.showMessageDialog(null,"註冊成功!");					
				}
			} catch (SQLException e) {
				JOptionPane.showMessageDialog(null, "對不起該用戶名已經有了!");
				e.printStackTrace();
			}
		}
		/*
		public boolean compare(String username,String password) {
			boolean m = false;
			String sql ="select password from user where username=\""+username+"\"";
			
		}
		
		 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		

	}
*/
		public boolean compare(String username, String password) {
			// TODO Auto-generated method stub
			boolean m = false;
			String sql="select password from user where username = \"" +username+"\"";
			try {
				res = statement.executeQuery(sql);
				if (res.next()) {
					String pa=res.getString(1);
					System.out.println(pa + " " +password);
					if (pa.equals(password)) {
						m =true;
					}else {
						JOptionPane.showMessageDialog(null,"密碼錯誤!");
					}
				}else {
						JOptionPane.showMessageDialog(null,"用戶名稱不存在");
					}
				res.close();
				con.close();
				statement.close();
			}catch (SQLException e) {
				e.printStackTrace();
			}
			return m;
		}
		public boolean update(String username1, String password1, String newpassword) {
			// TODO Auto-generated method stub
			boolean judge = false;
			boolean s =compare (username1,password1);
			if(s) {
				String sql ="update user set password=\""+newpassword+"\"where username=\""+username1+"\"";
				try {
					con = DriverManager.getConnection(url,name,passwd);
					statement =con.createStatement();
					int a =statement.executeUpdate(sql);
					if (a==1) {
						JOptionPane.showMessageDialog(null, "密碼修改成功!");
						judge = true;
					}
					con.close();
					statement.close();
				}catch (SQLException e) {
					JOptionPane.showMessageDialog(null, "用戶不存在!");
					e.printStackTrace();
				}
			}else {
				JOptionPane.showMessageDialog(null, "修改失敗");
			}
			return judge;
		}
		//刪除用戶訊息
		public void delete(String username, String password) {
			// TODO Auto-generated method stub
			if (compare(username,password)) {
				JOptionPane.showMessageDialog(null, "已經完成刪除");
			}else {
				return;
			}
			try {
				con = DriverManager.getConnection(url,name,passwd);
				statement = con.createStatement();
				String sql = "delete from user where username =\""+ username +"\"";
				statement.executeUpdate(sql);
				int a = statement.executeUpdate(sql);
				con.close();
				statement.close();
			}catch (SQLException e) {
				JOptionPane.showMessageDialog(null, "不存在該用戶!");
				e.printStackTrace();
			}
		
		}
}
```

#1224

```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class cal extends JFrame implements ActionListener{
	JTextField numberfield;
	String numberstring="";
	double number;
	char buttonname[]= {'7','8','9','/',
			            '4','5','6','*',
			            '1','2','3','-',
			            '0','.','=','+'};
	JButton button[]=new JButton[16];
	char operator;
	boolean point;
	
	public cal()
	{
		super ("計算機");
		Container c = getContentPane();
		c.setLayout(new BorderLayout());
		
		JPanel p = new JPanel();
		
		numberfield =new JTextField("0.0");
		numberfield.setHorizontalAlignment(JTextField.RIGHT);
		
		p.setLayout(new GridLayout(4,4));
		
		for (int i=0;i<16;i++) {
			button[i] =new JButton (buttonname[i]+"");
			p.add(button[i]);
			button[i].addActionListener(this);
		}
		c.add("North",numberfield);
		c.add("Center",p);
		
		setSize(200,200);
		setVisible(true);
	}

	public void actionPerformed(ActionEvent event) {
		// TODO Auto-generated method stub
		if (((JButton)event.getSource()).getText().charAt(0)=='.'){
			if(!point) {
				if(numberstring.equals(""))
					numberstring = "0";
				
				numberstring +=".";
				numberfield.setText(numberstring);
				point = true;
			}
		}else if (((JButton)event.getSource()).getText().charAt(0)<='9' &&
				  ((JButton)event.getSource()).getText().charAt(0)>='0') {
				numberstring+= ((JButton)event.getSource()).getText().charAt(0)+"";
				numberfield.setText(numberstring);
		}else {
			point=false;
			numberstring="";
			numberfield.setText(operation(number,
					Double.parseDouble(numberfield.getText()),operator)+"");
			operator=((JButton)event.getSource()).getActionCommand().charAt(0);
			if(((JButton) event.getSource()).getText().charAt(0)!='=')
				number=Double.parseDouble(numberfield.getText());
		}
	}
    
    	
	
public double operation(double number1,double number2,char operator)
{
	switch(operator)
	{
	case '+':
		return number1+number2;
	case '-':
		return number1-number2;
	case '*':
		return number1*number2;
	case '/':
		return number1/number2;
	default:
		return number2;
	}
}
public static void main(String[] args) {
	cal a=new cal();
	a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}
```

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class SimpleNotepad extends JFrame implements ActionListener{
	private JTextArea txt=new JTextArea();
	private JMenuBar newMenuBar(){
	JMenuBar menubar=new JMenuBar();
	String[] titles= {"File","test"};
	String[][]elements= {{"New","Open","Save"},{"LoL"}};
	for(int i=0;i<titles.length;i++) {
		String title=titles[i];
		String []element=elements[i];
		menubar.add(newMenu(title,element));
	}
	return menubar;
}

	private SimpleNotepad() {
        setTitle("untitled - Notepad");  
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());  //設定圖形介面外觀
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        setSize(800, 600); 
        setJMenuBar(newMenuBar());
        JScrollPane scroller = new JScrollPane(txt);
        add(scroller); 
        
    }
private JMenu newMenu(String title,String[]elements) {
	JMenu menu=new JMenu(title);
	for(String element:elements) {
		JMenuItem menuitem=new JMenuItem(element);
		menu.add(menuitem);
		menuitem.addActionListener((ActionListener) this);
	}
	return menu;
}

public static void main(String[] args) {
	new SimpleNotepad().setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
	// TODO Auto-generated method stub
	
}}







000000000000000000000000000000000000

class Filter extends javax.swing.filechooser.FileFilter implements FileFilter{
	public boolean accept(File file) {
		return file.getName().endSwith(".txt") || file.getName().endswith(".java");




000000000000000000000000000000000000000000000000000

		}else if (cmd.equals("Open")) {
			JFileChooser chooser = new JFileChooser();
			chooser.setFileFilter(new Filter());
			int option = chooser.showOpenDialog(this);
			if (option ==JFileChooser.APPROVE_OPTION) {
				try {
					Scanner scanner = new Scanner(chooser.getSelectedFile());
					while (scanner.hasNext()) {
						String data =scanner.nextLine();
						txt.setText(data);
					}
					setTitle(chooser.getSelectedFile().getName());
					scanner.close();
				}catch (FileNotFoundException e) {e.printStackTrace();}}}}
                
                
                
                
                
                
                ----------------
            import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.*;

public class SimpleNotepad extends JFrame implements ActionListener{
private JTextArea txt=new JTextArea();
private JMenuBar newMenuBar(){
JMenuBar menubar=new JMenuBar();
String[] titles= {"File","test"};
String[][]elements= {{"New","Open","Save"},{"LoL"}};
for(int i=0;i<titles.length;i++) {
    String title=titles[i];
    String []element=elements[i];
    menubar.add(newMenu(title,element));
}
return menubar;
}

private SimpleNotepad() {
    setTitle("untitled - Notepad");  
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());  //設定圖形介面外觀
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (UnsupportedLookAndFeelException e) {
        e.printStackTrace();
    }
    setSize(800, 600); 
    setJMenuBar(newMenuBar());
    JScrollPane scroller = new JScrollPane(txt);
    add(scroller); 

}
private JMenu newMenu(String title,String[]elements) {
JMenu menu=new JMenu(title);
for(String element:elements) {
    JMenuItem menuitem=new JMenuItem(element);
    menu.add(menuitem);
    menuitem.addActionListener((ActionListener) this);
}
return menu;
}



public static void main(String[] args) {
new SimpleNotepad().setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
ActionEvent actionEvent;
// TODO Auto-generated method stub
String cmd=actionEvent.getActionCommand();
if(cmd.equals("Save")) {
    JFileChooser chooser=new JFileChooser();
    int option=chooser.showSaveDialog(this);
    if(option==JFileChooser.APPROVE_OPTION) {
        try {
            BufferedWriter buf=new BufferedWriter(new FileWriter(chooser.getSelectedFile().getAbsolutePath())); 
            buf.write(txt.getText());
            setTitle(chooser.getSelectedFile().getName());
            buf.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
    }else if(cmd.equals("Open")) {
        JFileChooser chooser1 = new JFileChooser();
        chooser1.setFileFilter(new Filter());
        int option = chooser1.showOpenDialog(this);
        if (option ==JFileChooser.APPROVE_OPTION) {
            try {
                Scanner scanner = new Scanner(chooser1.getSelectedFile());
                while (scanner.hasNext()) {
                    String data =scanner.nextLine();
                    txt.setText(data);
                }
                setTitle(chooser1.getSelectedFile().getName());
                scanner.close();
            }catch (FileNotFoundException e) {e.printStackTrace();}}}}

class Filter extends javax.swing.filechooser.FileFilter implements FileFilter{
public boolean accept(File file) {
    return file.getName().endsWith(".txt") || file.getName().endsWith(".java");
}
@Override
public String getDescription() {
    // TODO Auto-generated method stub
    return "Text File(.txt)";
}
}
}


