--- title: JAVA(進階程設-期中考後) tags: JAVA(進階程設-期中考後) --- # JAVA程式語言 --- 李鍾斌(進階程設-期中考後) > 【目次】 > [TOC] > --- ## 期中考解答 PDF :::success ![](https://i.imgur.com/b3ZpQ8c.png) ### Q01 ```java= import java.io.*; public class Exam01 { public static void main(String[] args) { try{ FileReader fr = new FileReader("in.txt"); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter("out.txt", false); BufferedWriter bw = new BufferedWriter(fw); String line; int i = 0; System.out.println("Name Math English"); String linelist [] = new String [4]; //宣告0,1,2,3 while ((line = br.readLine()) != null) { linelist[i] = line; System.out.println(linelist[i]); //使用0,1,2 i++; } bw.write("Name Math English"); bw.newLine(); for (int j = 2; j >= 0; j--){ //寫入2,1,0 bw.write(linelist[j]); bw.newLine(); } bw.close(); } catch (IOException e) { System.out.println(e);} } } ``` ```java= public class CScore { String name; int math; int eng; public CScore (){ } public CScore (String str, int m, int e){ name = str; math = m; eng = e; } } ``` ::: :::warning ![](https://i.imgur.com/y4GRMqK.png) ### Q02 ```java= public class CAdd { public static void main(String[] args) { CAddto ad1 = new CAddto(); CAddto ad2 = new CAddto(15); ad1.add(); ad2.add(); } } ``` ```java= public class CAddto extends CAdd { int upper; public CAddto(){ upper = 10; } public CAddto(int a){ upper = a; } public void add(){ int sum = 0; for (int i = 0; i <= upper; i++){ sum += i; } System.out.printf("1+2+...+%d=%d\n", upper, sum); } } ``` ::: :::info ![](https://i.imgur.com/NeEfI2d.png) ### Q03 ```java= import java.util.*; public class Exam03 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.printf("=== 第一位 ===\n"); //第一組 日期資料 BDate bd1 = new BDate(); System.out.printf("year = "); bd1.year = sc.nextInt(); System.out.printf("month = "); bd1.month = sc.nextInt(); System.out.printf("day = "); bd1.day = sc.nextInt(); bd1.calAge(bd1.year); //印出 "年齡" bd1.printDate(bd1.year, bd1.month, bd1.day); bd1.leap(bd1.year); //印出 "平/閏年" System.out.printf("\n=== 第二位 ===\n"); //第二組 日期資料 BDate bd2 = new BDate(); System.out.printf("year = "); bd2.year = sc.nextInt(); System.out.printf("month = "); bd2.month = sc.nextInt(); System.out.printf("day = "); bd2.day = sc.nextInt(); bd2.calAge(bd2.year); bd2.printDate(bd2.year, bd2.month, bd2.day); bd2.leap(bd2.year); System.out.printf("\n=== 第三位 ===\n"); //第三組 日期資料 BDate bd3 = new BDate(); bd3.year = 1990; bd3.month = 1; bd3.day = 1; bd3.calAge(bd3.year); bd3.printDate(bd3.year, bd3.month, bd3.day); bd3.leap(bd3.year); sortAge(bd1.year, bd2.year, bd3.year); } public static void sortAge(int a, int b, int c){ //印出年齡最大的一位。用西元年來比較 System.out.printf("\n=== 年齡最大者 ===\n"); if (a < b && a < c){ System.out.println("第一位"); } else if (b < a && b < c){ System.out.println("第二位"); } else if (c < a && c < b) { System.out.println("第三位"); } } } Output: === 第一位 === year = 1880 month = 3 day = 4 年齡:139 Year Month Day 1880 3 4 閏年 === 第二位 === year = 1840 month = 5 day = 4 年齡:179 Year Month Day 1840 5 4 閏年 === 第三位 === 年齡:29 Year Month Day 1990 1 1 平年 === 年齡最大者 === 第二位 ``` ```java= public class BDate { int year, month, day; int age; //年齡,在排序時用來比較 public BDate(){ int year = 1990; int month = 1; int day = 1; } public int calAge(int y){ //計算年齡(計算至今日的實際歲數,只計年不計月) int age; age = 2019 - y; System.out.println("年齡:" + age); return age; } public void printDate(int y, int m, int d){ //列印日期資料 System.out.printf("Year\t Month\t Day\n"); System.out.println(y + "\t " + m + "\t " + d + "\n"); } public void leap (int y){ //判斷並列印變數year是否為閏年:boolean if (y % 4 != 0) System.out.println("平年"); else{ if (y % 100 != 0) System.out.println("閏年"); else{ if (y % 400 != 0) System.out.println("平年"); else System.out.println("閏年"); } } } } ``` ::: # 2019-04-22 class * 動態陣列 vs. 之前介紹的Array(必須宣告空間有多大) * 動態陣列 * 優點:不需事先宣告空間有多大 * 缺點:比傳統的陣列慢、效率差。 * 傳統的陣列 (之前介紹的Array) * 缺點:必須事先宣告空間有多大 ## Java 資料處理 -- ==讀取數值== * 資料集:`test.txt` ``` 170.0 80.0 90.5 172.5 67.2 81.4 210.1 104.9 100.3 ``` * 以"空格/tab"分開,將每個元素分別放進 tempArray ```java= tempArray = tempstring.split("\\s"); //以"空格"分開 tempArray = tempstring.split("\\t"); //以"tab"分開 ``` ```java= import java.io.*; import java.util.ArrayList; public class Week10 { public static void main(String[] args) { try{ FileReader fr = new FileReader("in.txt"); BufferedReader br = new BufferedReader(fr); String line, tempstring; String [] tempArray = new String[3]; //宣告0,1,2 ArrayList myList = new ArrayList(); int i = 0; //每次讀取一整行 170.0 80.0 90.5 while ( (line = br.readLine()) != null ){ tempstring = line; tempArray = tempstring.split("\\s"); //System.out.println(tempArray[0]+"==="); //170.0=== //172.5=== //210.1=== for (i = 0; i < tempArray.length; i++){ myList.add(tempArray[i]); //System.out.println(tempArray[i]+"---"); //170.0--- //80.0--- //90.5--- ... } } //動態陣列 .size() = 傳統陣列 .length() int k = myList.size()/3; //k = 3組 int count = 0; double [][] trans_array = new double [k][3]; for ( int x = 0; x < k; x++){ for (int y = 0; y < 3; y++){ trans_array[x][y] = Double.parseDouble((String)myList.get(count)); count++; System.out.println(trans_array[x][y]); } } System.out.println("----- Data Imported ------"); for ( int x = 0; x < k; x++){ for (int y = 0; y < 3; y++){ System.out.printf("%5.1f\t", trans_array[x][y]); } System.out.println(); } } catch (IOException e) { System.out.println(e);} } } Output: > run Week10 170.0 80.0 90.5 172.5 67.2 81.4 210.1 104.9 100.3 ----- Data Imported ------ 170.0 80.0 90.5 172.5 67.2 81.4 210.1 104.9 100.3 ``` --- # 2019-04-29 class ## Java 資料處理 -- ==讀取數值&字串== * 資料集: `irisdata .txt` ``` 5.1 3.5 1.4 0.2 setosa 4.9 3.0 1.4 0.2 setosa 4.7 3.2 1.3 0.2 setosa 4.6 3.1 1.5 0.2 setosa 5.0 3.6 1.4 0.2 setosa ... ``` ```java= import java.io.*; import java.util.ArrayList; public class Week11 { public static void main(String[] args) { try{ FileReader fr = new FileReader("irisdata.txt"); BufferedReader br = new BufferedReader(fr); String line, tempstring; String [] tempArray = new String[5]; //宣告0,1,2,3,4 ArrayList myList = new ArrayList(); int i = 0; //每次讀取一整行 5.1 3.5 1.4 0.2 setosa while ( (line = br.readLine()) != null ){ tempstring = line; tempArray = tempstring.split("\\t"); //System.out.println(tempArray[0]+"==="); //5.1=== //4.9=== //4.7=== ... for (i = 0; i < tempArray.length; i++){ myList.add(tempArray[i]); //System.out.println(tempArray[i]+"---"); //5.1--- //3.5--- //1.4--- //0.2--- //setosa--- ... } } //動態陣列 .size() = 傳統陣列 .length() int k = myList.size()/5; //k 組 //第 k 列 (橫) int count = 0; double [][] trans_array = new double [k][4]; //for 5.1 3.5 1.4 0.2 String [] str_trans_array = new String [k]; //for setosa for ( int x = 0; x < k; x++){ for (int y = 0; y < 4; y++){ trans_array[x][y] = Double.parseDouble((String)myList.get(count)); count++; } str_trans_array[x] = (String)myList.get(count); count++; } System.out.println("-------- Data Imported ---------"); System.out.printf("花萼長度\t花萼寬度\t花瓣長度\t花瓣寬度\t屬種\n"); for ( int x = 0; x < k; x++){ System.out.printf("%5.1f\t%5.1f\t%5.1f\t%5.1f\t%s\n", trans_array[x][0], trans_array[x][1], trans_array[x][2], trans_array[x][3], str_trans_array[x]); } } catch (IOException e) { System.out.println(e); } } } Output: -------- Data Imported --------- 花萼長度 花萼寬度 花瓣長度 花瓣寬度 屬種 5.1 3.5 1.4 0.2 setosa 4.9 3.0 1.4 0.2 setosa ... ``` * K-近鄰演算法 (K Nearest Neighbor, KNN):k個最近的鄰居 :::warning ## HW07:鳶尾花分類 (1NN) 1.利用課堂範例,將irisdata.txt匯入程式。 2.採用kNN方法(k=1),讓使用者由鍵盤輸入資料後判斷所屬亞種。 ```java= import java.util.*; import java.io.*; import java.util.ArrayList; public class Week10 { public static void main(String[] args) { try{ FileReader fr = new FileReader("irisdata.txt"); BufferedReader br = new BufferedReader(fr); String line, tempstring; String [] tempArray = new String[5]; //宣告0,1,2,3,4 ArrayList myList = new ArrayList(); int i = 0; //每次讀取一整行 5.1 3.5 1.4 0.2 setosa while ( (line = br.readLine()) != null ){ tempstring = line; tempArray = tempstring.split("\\t"); //System.out.println(tempArray[0]+"==="); //5.1=== //4.9=== //4.7=== ... for (i = 0; i < tempArray.length; i++){ myList.add(tempArray[i]); //System.out.println(tempArray[i]+"---"); //5.1--- //3.5--- //1.4--- //0.2--- //setosa--- ... } } //動態陣列 .size() = 傳統陣列 .length() int k = myList.size()/5; //k 組 //第 k 列 (橫) int count = 0; //for 5.1 3.5 1.4 0.2 double [][] trans_array = new double [k][4]; //for setosa String [] str_trans_array = new String [k]; for ( int x = 0; x < k; x++){ for (int y = 0; y < 4; y++){ trans_array[x][y] = Double.parseDouble((String)myList.get(count)); count++; } str_trans_array[x] = (String)myList.get(count); count++; } /* --- 使用者 input (1筆) --- */ System.out.println("請輸入 一筆 未知鳶尾花的資料"); Double [] unknown = new Double[4]; //0,1,2,3 Scanner sc = new Scanner(System.in); System.out.printf("花萼長度:"); unknown [0] = sc.nextDouble(); System.out.printf("花萼寬度:"); unknown [1] = sc.nextDouble(); System.out.printf("花瓣長度:"); unknown [2] = sc.nextDouble(); System.out.printf("花瓣寬度:"); unknown [3] = sc.nextDouble(); /* String [] kind = new String [1]; //0 System.out.printf("請輸入花萼屬種:"); kind[0] = sc.next(); System.out.printf(kind[0]+'\n'); */ // KNN, k=1 // 計算"每組(每一橫列)"與"使用者 input"之差的平方和。共 k 組 Double [] iris_all = new Double [k]; for ( int x = 0; x < k; x++){ iris_all[x] = Math.sqrt( Math.pow(trans_array[x][0] - unknown[0], 2) + Math.pow(trans_array[x][1] - unknown[1], 2) + Math.pow(trans_array[x][2] - unknown[2], 2) + Math.pow(trans_array[x][3] - unknown[3], 2) ); count++; } int index = 1; //實際上為第幾筆 Double min = iris_all[0]; for (int j = 0; j < k; j++) { if (iris_all[j] < min) { //如果該筆資料<目前最低分 min = iris_all[j]; //該筆設為目前最低分 index = j + 1; System.out.printf("%.5f\n", iris_all[j]); } } System.out.printf("KNN k = 1 =>\n"); System.out.printf( "該資料為第 %2d筆:\n%5.1f\t%5.1f\t%5.1f\t%5.1f\t%s\n", index, trans_array[index-1][0], trans_array[index-1][1], trans_array[index-1][2], trans_array[index-1][3], str_trans_array[index-1]); } catch (IOException e) { System.out.println(e);} } } Output: 請輸入 一筆 未知鳶尾花的資料 花萼長度:5.10001 花萼寬度:3.4 花瓣長度:1.5 花瓣寬度:0.2 0.10001 0.00001 KNN k = 1 => 該資料為第 40筆: 5.1 3.4 1.5 0.2 setosa ``` ::: --- # 2019-05-06 class ## Eclipse Java Photon ==Java== * Create Java 【Project:proj】 -> 【Class:Test】 ![](https://i.imgur.com/9ZS1CxT.png =400x300) ![](https://i.imgur.com/lQ0U5iZ.png =500x500) ![](https://i.imgur.com/bHgYsIH.png) * 改變【字體大小】 ![](https://i.imgur.com/eufScsN.png) ## ==Window Builder 1.9.1== * 安裝:help -> Eclipse Marketplace -> Search "Window Builder" -> 【Window Builder 1.9.1】 * 建立:Create Java 【Project:WinTest】 -> New - ==【Other...】== * -> WindowBuilder - Swing Designer - ==Application Window== ![](https://i.imgur.com/XVnILMZ.png =400x250) ![](https://i.imgur.com/OJc9jVu.png) * JButton ![](https://i.imgur.com/54kddtn.png) * Set layout -> ==Absolute layout== ![](https://i.imgur.com/bx32BPK.png =300x200) * Properties: * 該按鈕真正的名字(Variable) ![](https://i.imgur.com/ZRUqHQJ.png) * 寫按鈕的事件: * performed 點兩下後,把事件寫進按鈕裡。 ![](https://i.imgur.com/LLzYmrF.png) :::success ## ==Window Builder -- BMI計算== ![](https://i.imgur.com/NfwYrI3.png) ![](https://i.imgur.com/Ty5x0HW.png) ```java= btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double height = (Double.parseDouble(h1.getText())); double weight = (Double.parseDouble(w2.getText())); double bmi = weight/((height/100.0)*(height/100.0)); java.text.DecimalFormat df = new java.text.DecimalFormat("#.00"); String s = df.format(bmi); bmi3.setText(s); System.out.println(s); } }); ``` --- ### HW08:視窗化BMI計算 ![](https://i.imgur.com/EuSM42d.png) ```java= btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double height = (Double.parseDouble(h1.getText())); double weight = (Double.parseDouble(w2.getText())); double bmi = weight/((height/100.0)*(height/100.0)); if (bmi < 20) bmi_judge.setText("體重過輕"); else if (bmi < 25) bmi_judge.setText("體重正常"); else if (bmi < 30) bmi_judge.setText("體重過重"); else bmi_judge.setText("go to see a doctor"); java.text.DecimalFormat df = new java.text.DecimalFormat("#.00"); String s = df.format(bmi); bmi3.setText(s); System.out.println(s); } }); ``` ::: --- # 2019-05-13 class ## Window Builder ![](https://i.imgur.com/yV46S2H.png) * Button:【請按...】 ```java= public void actionPerformed(ActionEvent e) { int m = (Integer.parseInt(text1.getText())); //month int d = (Integer.parseInt(text2.getText())); //day if (m == 1 & (d >= 21 & d <= 31)) text3.setText("水瓶座"); if (m == 2 & (d >= 1 & d <= 19)) text3.setText("水瓶座"); if (m == 2 & (d >= 20 & d <= 29)) text3.setText("雙魚座"); if (m == 3 & (d >= 1 & d <= 20)) text3.setText("雙魚座"); if (m == 3 & (d >= 21 & d <= 31)) text3.setText("牡羊座"); if (m == 4 & (d >= 1 & d <= 20)) text3.setText("牡羊座"); if (m == 4 & (d >= 21 & d <= 30)) text3.setText("金牛座"); if (m == 5 & (d >= 1 & d <= 21)) text3.setText("金牛座"); if (m == 5 & (d >= 22 & d <= 31)) text3.setText("雙子座"); if (m == 6 & (d >= 1 & d <= 21)) text3.setText("雙子座"); if (m == 6 & (d >= 22 & d <= 30)) text3.setText("巨蟹座"); if (m == 7 & (d >= 1 & d <= 23)) text3.setText("巨蟹座"); if (m == 7 & (d >= 24 & d <= 31)) text3.setText("獅子座"); if (m == 8 & (d >= 1 & d <= 23)) text3.setText("獅子座"); if (m == 8 & (d >= 24 & d <= 31)) text3.setText("處女座"); if (m == 9 & (d >= 1 & d <= 23)) text3.setText("處女座"); if (m == 9 & (d >= 24 & d <= 30)) text3.setText("天枰座"); if (m == 10 & (d >= 1 & d <= 23)) text3.setText("天枰座"); if (m == 10 & (d >= 24 & d <= 31)) text3.setText("天蠍座"); if (m == 11 & (d >= 1 & d <= 22)) text3.setText("天蠍座"); if (m == 11 & (d >= 23 & d <= 30)) text3.setText("射手座"); if (m == 12 & (d >= 1 & d <= 22)) text3.setText("射手座"); if (m == 12 & (d >= 23 & d <= 31)) text3.setText("摩羯座"); if (m == 1 & (d >= 1 & d <= 22)) text3.setText("摩羯座"); } ``` * 一鍵清空 ```java= public void actionPerformed(ActionEvent e) { text1.setText(""); text2.setText(""); text3.setText(""); } ``` --- ## 打包Java程式 * File -> Export... -> Java - ==Runnable JAR file== * 1 -> 打包成可執行檔(只有==執行檔==) * 3 -> 打包成可執行檔 & 把外部函式庫也一併打包(==執行檔==+==外部函式庫==) ![](https://i.imgur.com/2ecCmYQ.png) --- ## 開啟檔案 ![](https://i.imgur.com/500KpHu.png) ```java= import javax.swing.JFileChooser; import java.io.File; public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); File selectedFile = null; //叫出fileChooser int returnValue = fileChooser.showOpenDialog(null); //判斷是否選擇檔案 if (returnValue == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); //指派給file System.out.println(selectedFile.getName()); //印出檔名 text_file.setText(selectedFile.getName()); } } ``` --- # 2019-05-20 class ## Window Builder (檔案處理 + 讀檔) :::success ### HW09:視窗程式-檔案處理 * 程式要求: 1. 由FileChooser讓使用者自行選擇匯入資料檔 2. 再根據使用者鍵盤輸入之出生月日,計算資料檔中與使用者同星座的人數 * 檔案 ``` Bessy 3 28 Ariel 5 2 Cindy 9 9 ... ``` * 物件:`text_m` `text_d` `text3` `text4` `text_file` ![](https://i.imgur.com/fepmv1W.png =345x250) ![](https://i.imgur.com/lGIQPGA.png) * ==< Int to Str >== ``` 1.) String s = String.valueOf(i); 2.) String s = Integer.toString(i); 3.) String s = "" + i; ```` ```java= import javax.swing.JFileChooser; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public void actionPerformed(ActionEvent e) { int m = (Integer.parseInt(text_m.getText())); //month int d = (Integer.parseInt(text_d.getText())); //day String my_sign = dochi(m, d); text3.setText(my_sign); System.out.println(my_sign + "--"); JFileChooser fileChooser = new JFileChooser(); File selectedFile = null; int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); System.out.println(selectedFile.getName()); text_file.setText(selectedFile.getName()); } FileReader fr = null; try{ fr = new FileReader(selectedFile); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader br = new BufferedReader(fr); String line, tempstring; String [] tempArray = new String [3]; ArrayList myList = new ArrayList(); String [] sign_List = new String [3]; int i = 0; int count_sign = 0; try { while ((line = br.readLine()) != null) { tempstring = line; tempArray = tempstring.split("\\s"); for (i = 0; i < tempArray.length; i++){ myList.add(tempArray[i]); //System.out.println(tempArray[i]+"=="); //System.out.println(myList+"--"); } for (i = 0; i < tempArray.length/3; i = i + 3) { if (i < 3) { System.out.println(tempArray[1]); System.out.println(tempArray[2]); int m1 = Integer.parseInt(tempArray[1]); int d1 = Integer.parseInt(tempArray[2]); String other_sign = dochi(m1, d1); //System.out.println(other_sign + "===="); sign_List[i] = other_sign; System.out.println(sign_List[i] + "vvvv"); for (i = 0; i < sign_List.length; i++) { if (sign_List[i] == my_sign){ count_sign += 1; } text4.setText(String.valueOf(count_sign)); } } } } } catch (IOException e1) { e1.printStackTrace(); } } public String dochi(int m, int d) { int sign_case = 0; if (m == 1 & (d >= 21 & d <= 31)) sign_case = 1; if (m == 2 & (d >= 1 & d <= 19)) sign_case = 1; if (m == 2 & (d >= 20 & d <= 29)) sign_case = 2; if (m == 3 & (d >= 1 & d <= 20)) sign_case = 2; if (m == 3 & (d >= 21 & d <= 31)) sign_case = 3; if (m == 4 & (d >= 1 & d <= 20)) sign_case = 3; if (m == 4 & (d >= 21 & d <= 30)) sign_case = 4; if (m == 5 & (d >= 1 & d <= 21)) sign_case = 4; if (m == 5 & (d >= 22 & d <= 31)) sign_case = 5; if (m == 6 & (d >= 1 & d <= 21)) sign_case = 5; if (m == 6 & (d >= 22 & d <= 30)) sign_case = 6; if (m == 7 & (d >= 1 & d <= 23)) sign_case = 6; if (m == 7 & (d >= 24 & d <= 31)) sign_case = 7; if (m == 8 & (d >= 1 & d <= 23)) sign_case = 7; if (m == 8 & (d >= 24 & d <= 31)) sign_case = 8; if (m == 9 & (d >= 1 & d <= 23)) sign_case = 8; if (m == 9 & (d >= 24 & d <= 30)) sign_case = 9; if (m == 10 & (d >= 1 & d <= 23)) sign_case = 9; if (m == 10 & (d >= 24 & d <= 31)) sign_case = 10; if (m == 11 & (d >= 1 & d <= 22)) sign_case = 10; if (m == 11 & (d >= 23 & d <= 30)) sign_case = 11; if (m == 12 & (d >= 1 & d <= 22)) sign_case = 11; if (m == 12 & (d >= 23 & d <= 31)) sign_case = 12; if (m == 1 & (d >= 1 & d <= 22)) sign_case = 12; String sign = ""; switch (sign_case){ case 1: sign = "水瓶座"; break; case 2: sign = "雙魚座"; break; case 3: sign = "牡羊座"; break; case 4: sign = "金牛座"; break; case 5: sign = "雙子座"; break; case 6: sign = "巨蟹座"; break; case 7: sign = "獅子座"; break; case 8: sign = "處女座"; break; case 9: sign = "天枰座"; break; case 10: sign = "天蠍座"; break; case 11: sign = "射手座"; break; case 12: sign = "摩羯座"; break; default: sign = "???"; break; } return sign; } ``` ::: --- # 2019-05-27 class ## ==[Java JFugue](http://www.jfugue.org/)== * 安裝並使用:右鍵 -> Build Path - ==Configure Build Path...== -> Libraries - ==Add External JARs...== -> Apply and Close * [The Complete Guide to JFugue](http://www.jfugue.org/4/jfbmrkklprpp/TheCompleteGuideToJFugue-v1.pdf) :::warning * Pitch相關 * 休止符:R * 升記號:# * 降記號:b * 分部:V * V0 … V1… * 樂器:I * I[Piano]… I[Flute]… * Duration相關 * 四拍:w (或qqqq) * 二拍:h (或qq) * 一拍:q * 半拍:i * 四分之一拍:s * 八分之一拍:t * 16分之一拍:x * 32分之一拍:o * 附點:. ::: :::success ### HW10:Audio練習 ```java= import org.jfugue.player.Player; public class HelloWorld { public static void main(String[] args) { Player player = new Player(); player.play("C D E F G A B"); } } ``` ```java= import org.jfugue.player.Player; import org.jfugue.pattern.Pattern; public class Audio { public static void main(String[] args) { /* Pattern p1 = new Pattern("Eq Ch. | Dq Eq Dq Cq" ).setVoice(0).setInstrument("Piano"); Pattern p2 = new Pattern("Rw | GmajQ CmajQ" ).setVoice(1).setInstrument("Flute"); */ Pattern p1 = new Pattern("V0 I[Piano] Eq Ch. | Dq Eq Dq Cq"); Pattern p2 = new Pattern("V1 I[Flute] Rw | GmajQ CmajQ"); Player player = new Player(); player.play(p1, p2); } } ``` ::: --- # 2019-06-03 class ## ==Java JFugue (記憶遊戲)== ```java= import java.util.Scanner; import org.jfugue.player.Player; public class audio { public static void main(String[] args) { Player player = new Player(); Scanner sc = new Scanner(System.in); String q = "R "; // question String a = "R "; // answer int note; boolean more = true; while (more) { note = (int)(Math.random()*8); switch (note) { case 0: q += " C4"; break; case 1: q += " D4"; break; case 2: q += " E4"; break; case 3: q += " F4"; break; case 4: q += " G4"; break; case 5: q += " A4"; break; case 6: q += " B4"; break; case 7: q += " C5"; break; default: System.out.println("Error!"); } System.out.println(q); player.play(q); int dummy = sc.nextInt(); //User input their answer. } } } Output: R G4 1 R G4 B4 2 R G4 B4 D4 1 R G4 B4 D4 F4 ... ``` :::info * [取出字串中的字元:str.charAt(0);](https://blog.csdn.net/ammmd/article/details/3014251) ``` String str = "abc"; char ch = str.charAt(0); //ch = a char ch2 = str.charAt(1); //ch2 = b ``` * [使用Scanner,讀取字串 (==nextLine()== vs. ==next()==)](http://www.runoob.com/java/java-scanner-class.html) ```java= import java.util.Scanner; public class ttt { public static void main(String[] args) { String str1, str2; Scanner sc = new Scanner(System.in); System.out.print("請輸入一字串:"); str1 = sc.nextLine(); System.out.println("您輸入的字串一為:\n" + str1 ); System.out.println("----------------"); System.out.print("請輸入一字串(不含空白字元、空白鍵、Tab):"); str2 = sc.next(); System.out.println("您輸入的字串一為:\n" + str2 ); } } Output: 請輸入一字串:hell ooo 您輸入的字串一為: hell ooo ---------------- 請輸入一字串(不含空白字元、空白鍵、Tab):hell ooo 您輸入的字串一為: hell ``` * 讀取檔案中的內容:==br.readLine()== ```java= import java.io.*; public class StringReaderDemo { public static void main(String[] args) { String s = "Hello World"; StringReader sr = new StringReader(s); try { for (int i = 0; i < 5; i++) { char c = (char) sr.read(); System.out.print("" + c); } sr.close(); } catch (IOException ex) { ex.printStackTrace(); } } } ``` ::: :::success ### HW 11:音感記憶遊戲 ```java= import java.util.*; import org.jfugue.player.Player; public class audio { public static void main(String[] args) { Player player = new Player(); Scanner sc = new Scanner(System.in); System.out.println(" --- 絕對音感 + 記憶遊戲 --- "); /* String song = "V0 I[Flute] Ci Di Ei Fi Gq Ai Fi Ei Ri Di Ri Ch "; song += "V1 I[Music_Box] CmajQQQ FmajQ CmajQ RQ CmajQQ"; player.play(song); */ String q = "R "; String a = "R "; int note; boolean more = true; while (more) { note = (int)(Math.random()*8); switch (note) { case 0: q += " C4"; break; case 1: q += " D4"; break; case 2: q += " E4"; break; case 3: q += " F4"; break; case 4: q += " G4"; break; case 5: q += " A4"; break; case 6: q += " B4"; break; case 7: q += " C5"; break; default: System.out.println("Error!"); } System.out.println(q); player.play(q); int dummy = sc.nextInt(); switch (dummy) { case 0: a += " C4"; break; case 1: a += " D4"; break; case 2: a += " E4"; break; case 3: a += " F4"; break; case 4: a += " G4"; break; case 5: a += " A4"; break; case 6: a += " B4"; break; case 7: a += " C5"; break; default: System.out.println("Error!"); } if (q.equals(a)) { System.out.println("identical !"); } else { System.out.println("not same"); System.out.println("遊戲結束"); break; } } } } Output: --- 絕對音感 + 記憶遊戲 --- R D4 1 identical ! R D4 B4 6 identical ! R D4 B4 B4 6 identical ! R D4 B4 B4 F4 8 Error! not same 遊戲結束 ``` ::: --- # 2019-06-10 class ## 預備環境:`XAMPP` & `Connector/J` * [安裝 XAMPP](https://www.apachefriends.org/zh_tw/index.html):Apache + MariaDB + PHP + Perl `xampp-windows-x64-7.3.6-0-VC15-installer.exe` * Apache:網頁伺服器 * MySQL:資料庫 * phpmyadmin ![](https://i.imgur.com/gNxGv0z.png) * [下載 Connector/J](https://dev.mysql.com/downloads/connector/j/5.1.html): `mysql-connector-java-5.1.47-bin.jar` ## ==Eclipse 設定 JDBC 連接 MySQL資料庫== * 安裝並使用:右鍵 -> Build Path - ==Configure Build Path...== -> Libraries - ==Add External JARs...== - `【mysql-connector-java-5.1.47-bin.jar】` -> Apply and Close ![](https://i.imgur.com/m3SJbMu.png =350x450) ![](https://i.imgur.com/kJ4TrJv.png) * 建構式:直接執行與現在.java名稱相同的部分。 :::success ### HW12:JDBC連接MySQL練習 ```java= package db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class jdbcmysql { private Connection con = null; //Database objects //連接object private Statement stat = null; //執行,傳入之sql為完整字串 private ResultSet rs = null; //結果集 private PreparedStatement pst = null; //執行,傳入之sql為預儲之字申,需要傳入變數之位置 //先利用?來做標示 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.jdbc.Driver"); //註冊driver con = DriverManager.getConnection( "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=Big5", "root",""); //取得connection //jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=Big5 //localhost是主機名,test是database名 //useUnicode=true&characterEncoding=Big5使用的編碼 } catch(ClassNotFoundException e) { System.out.println("DriverClassNotFound :"+e.toString()); } catch(SQLException x) { System.out.println("Exception :"+x.toString()); } } //建立table的方式 //可以看看Statement的使用方式 public void createTable() { try { stat = con.createStatement(); stat.executeUpdate(createdbSQL); } catch(SQLException e) { System.out.println("CreateDB Exception :" + e.toString()); } finally { Close(); } } //新增資料 //可以看看PrepareStatement的使用方式 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("InsertDB Exception :" + e.toString()); } finally { Close(); } } //刪除Table, //跟建立table很像 public void dropTable() { try { stat = con.createStatement(); stat.executeUpdate(dropdbSQL); } catch(SQLException e) { System.out.println("DropDB Exception :" + e.toString()); } finally { Close(); } } //查詢資料 //可以看看回傳結果集及取得資料方式 public void SelectTable() { try { stat = con.createStatement(); rs = stat.executeQuery(selectSQL); System.out.println("ID\t\tName\t\tPASSWORD"); 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("DropDB Exception :" + e.toString()); } finally { Close(); } } //完整使用完資料庫後,記得要關閉所有Object //否則在等待Timeout時,可能會有Connection poor的狀況 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("Close Exception :" + e.toString()); } } public static void main(String[] args) { //測看看是否正常 jdbcmysql test = new jdbcmysql(); test.dropTable(); test.createTable(); test.insertTable("yku", "12356"); test.insertTable("yku2", "7890"); test.SelectTable(); } } Output: ID Name PASSWORD 1 yku 12356 2 yku2 7890 ``` :::