public class Ex 04Refactory public static void mainString
副程式重構範例 public class Ex 04_Refactory { public static void main(String[] args) { System. out. println("測試for迴圈"); for. Loop() ; System. out. println("溫度對照表"); Convert. Temp(20, 10) ; System. out. println("繩索對折次數計算"); Fold. Rope(100 f, 20 f) ; System. out. println("浮點數迭加 – 誤差累計"); error. Increment(0. 1, 100) ; System. out. println("階乘計算"); System. out. println("5!=" + n. Factorial(5)) ; System. out. println("九九乘法表"); Table 99() ; System. out. println("樂透彩自動選號"); for(int i=0; i<6; i++) { System. out. println("第"+(i+1)+"組號碼"); Lotto() ; } }
public static void for. Loop() {// 測試for迴圈 int total = 0; // 遞增for迴圈敘述 for (int i = 1; i <= 10; i++ ) { System. out. print("Number: " + i + " "); total += i; } System. out. println("n. Summary from 1 to 10: " + total); System. out. println(" --------- "); total = 0; // 重設總和變數 // 遞減for迴圈敘述 for (int i = 10; i >= 1; i-- ) { System. out. print("Number: " + i + " "); total += i; } System. out. println("n. Summary from 10 to 1: " + total); }
// 溫度對照表 public static void Convert. Temp(double c. Buttom, double c. Top, int n) { double c = c. Buttom ; double f; System. out. println("C F"); // while迴圈敘述 // while ( c <= 100 ) { // f = (9. 0 * c) / 5. 0 + 32. 0; while ( c <= c. Top ) { f = Cto. F(c) ; System. out. println(c + " " + f); // c += 10; c+=(c. Top-c. Buttom)/n ; } }
// 溫度對照表 public static void Convert. Temp(double c. Buttom, double c. Top, int n) { double c = c. Buttom ; double f; System. out. println("C F"); // while迴圈敘述 // while ( c <= 100 ) { // f = (9. 0 * c) / 5. 0 + 32. 0; while ( c <= c. Top ) { f = Cto. F(c) ; System. out. println(c + " " + f); // c += 10; c+=(c. Top-c. Buttom)/n ; } } public static double Cto. F(double c) {// 溫度轉換公式 C -> F double f = (9. 0 * c) / 5. 0 + 32. 0; return f ; } public static double Fto. C(double f) {// 溫度轉換公式 F -> C double c = (f - 32. 0) * 5. 0 / 9. 0 ; return c ; }
// 繩索對折次數計算 public static void Fold. Rope(float rope. Len, float sect. Len) { int count = 0; // 計算次數 // float len = 100. 0 f; float len = rope. Len ; // do/while迴圈敘述 do { System. out. println(count + " Length: " + len); count++; len /= 2. 0; // 對折繩索 } while ( len > sect. Len ); System. out. println("Folding Number: " + count); System. out. println("Final Length: " + len); }
// 浮點數迭加 – 誤差累計 public static void error. Increment(double ini. Value, double lim. Value) { // double d=0. 1; double d = ini. Value ; double sum=0. 0; // while(d<=10. 0){ while(d<=lim. Value){ sum=sum+d; System. out. println(d +"t"+sum + "t" + Math. round(sum*100)/100. 0); d = d + 0. 1; } }
public static int n. Factorial(int n) {// 階乘計算 int num = n; int prod = 1; int count = 1 ; // do/while迴圈敘述 do { System. out. println("Number: " + count); if (num == 0) break ; // 跳出迴圈 else prod *= count; count++; } while ( count <= num ); // System. out. println("5! = " + prod); return prod ; }
public static void Table 99() {// 九九乘法表 // 顯示標題列 System. out. print(" "); for (int i = 1; i <= 9; i++ ) System. out. print(i + " "); System. out. println(); // 巢狀迴圈-第一層while迴圈 int row = 0, col=0 ; while (row <= 9 ) { // 顯示欄標題 System. out. print(row + " "); for (col = 1; col <= 9; col++ ) { // 第二層for迴圈 System. out. print(row + "*" + col + "="); System. out. print(row*col + " "); if ( (row*col ) < 10 && col != 1 ) System. out. print(" "); // 調整顯示位置 } row++; // 計數器變數加一 System. out. println(); } }
public static void Lotto() {// 樂透彩自動選號 int[] lo = new int[6] ; boolean check ; int k = 1; do { for(int i=0; i<6; i++) lo[i] = ((int)(Math. random() * 1000)) % 49 + 1; check = false; for(int i=0; i<6; i++) { for(int j=i+1; j<6; j++) { if(lo[i] == lo[j]) check = true ; } } k++ ; } while(check) ; System. out. print("重號次數:" + k + "n樂透號碼:") ; for(int i=0; i<6; i++) System. out. print(lo[i] + "t") ; System. out. println() ; System. out. print("重新排序:") ; Bubble. Sort(lo) ; for(int i=0; i<6; i++) System. out. print(lo[i] + "t") ; System. out. println() ; }
public static int[] Bubble. Sort(int[] lo) {// 氣泡排序 for(int i=0; i<lo. length-1; i++) { for(int j=i+1; j<lo. length; j++) { if(lo[i] > lo[j]) { int big = lo[i] ; lo[i] = lo[j] ; lo[j] = big ; } } } return lo ; } }
public static void main(String[] args) { int ia = 10 ; int ib = ia ; ia = 20 ; System. out. println("ia="+ia+"tib="+ib) ; int[] a = {1, 4, 3, 5, 9} ; set. A(ia, a) ; System. out. println("a[] --> changed in set. A") ; for(int i=0; i<a. length; i++) { System. out. print(a[i] + "t") ; } System. out. println("ia = " + ia) ; ib = get. A(ia) ; System. out. println("Use get. A to return new value - input: " + ia + "treturn: " + ib) ; int[] b = get. B(a) ; System. out. println("Use get. B to return new value of input a[]na[]tb[]") ; for(int i=0; i<a. length; i++) { System. out. println(a[i] + "t" + b[i]) ; } } public static void set. A(int a 0, int[] a) { a 0 = a 0 * a 0 ; for(int i=0; i<a. length; i++) { a[i] = a[i] * 10 ; } } public static int get. A(int a 0) { return a 0*a 0 ; } public static int[] get. B(int[] a) { int[] b = a. clone() ; /* 複製陣列, 與clone同義 int[] b = new int[a. lenght] ; for(int i=0; i<b. length; i++) { b[i] = a[i] ; } */ for(int i=0; i<b. length; i++) { b[i] = b[i] * 10 ; } return b ; }
n 字元串流(Character. Stream)- n 字元串流是是一種適合人類閱讀(Human-readable)的串 流,Reader/Writer兩個類別分別讀取和寫入 16位元的字 元資料。 n n Buffer. Reader/Buffer. Writer:處理緩衝區I/O。 Input. Stream. Reader/Output. Stream. Writer: Input. Stream. Reader在讀取位元組資料後將它轉成字元資料, Ouput. Stream. Writer是將字元轉換成位元組資料。 File. Reader/File. Writer:處理檔案的I/O。 位元組串流(Byte. Stream)- n 位元組串流是一種電腦格式(Machine-formatted)串流, 可以讀取和寫入 8位元的位元組資料,也就是處理二進 位資料的執行檔、圖檔和聲音等。 n n n File. Input. Stream/File. Output. Stream:處理檔案的I/O。 Data. Input. Stream/Data. Output. Stream:讀取和寫入基本資料型 態的資料。 Buffer. Input. Stream/Buffered. Output. Stream:處理緩衝區I/O。
n 複製二進位元檔案(以Word檔為例) try { File. Input. Stream fis = new File. Input. Stream(new File("wordtest. doc" )); File. Output. Stream fos = new File. Output. Stream(new File("wordtest_bak. doc" )); int filesize = fis. available() ; byte[] buffer = new byte[1024] ; while(true) { if(fis. available() < 1024) { int remain ; do { remain = fis. read() ; fos. write(remain); } while(remain != -1) ; break ; } else { fis. read(buffer) ; fos. write(buffer) ; } } fis. close() ; fos. close() ; } catch (Exception e) {}
import java. io. File; import java. io. File. Input. Stream; import java. io. File. Output. Stream; import java. io. File. Writer; import java. util. Date; import java. util. Scanner; public class Ex 04_File. Test { public static void main(String[] args) { // File and directory property String filepath = "H: \Course_Data\Comp. Lang\Java. Example\src\" ; String filename = "testfile. txt" ; File f = new File(filename) ; if(f. exists()) { System. out. println(f. get. Name()) ; System. out. println(f. get. Path()) ; System. out. println(f. get. Absolute. Path()) ; } else { System. out. println("The file is not existing") ; } String[] filenames ; File fs = new File(filepath) ; 檔案存取範例
if(fs. is. Directory()) { filenames = fs. list() ; for(int i=0; i<filenames. length; i++) { File fname = new File(filenames[i]) ; String dir = "[" ; if(fname. is. Directory()) dir = dir + "d" ; else dir = dir + "-" ; if(fname. is. File()) dir = dir + "f" ; else dir = dir + "-" ; if(fname. can. Read()) dir = dir + "r" ; else dir = dir + "-" ; if(fname. can. Write()) dir = dir + "w" ; else dir = dir + "-" ; if(fname. is. Hidden()) dir = dir + "h" ; else dir = dir + "-" ; dir = dir + "]" ; long time = fname. last. Modified() ; Date date = new Date(time) ; System. out. print(dir + "t" + filenames[i] + "t" + fname. length() + " Bytest" + date + "n") ; } } else { System. out. println("It is not a directory") ; }
// Read text file Scanner sc ; try { sc = new Scanner(f) ; while(sc. has. Next()) { System. out. println(sc. next. Line()) ; } } catch(Exception e) {} // Write text file File fcopy = new File(filepath + "testcopy. txt"); File. Writer fw ; try { if(fcopy. exists()) { fw = new File. Writer(fcopy, true) ; } else { fcopy. create. New. File() ; fw = new File. Writer(fcopy) ; } sc = new Scanner(f) ; while(sc. has. Next()) { fw. write(sc. next. Line()+"n") ; } fw. close() ; } catch(Exception e) {}
// Rename file String newfname = filepath + "testnew. txt" ; fcopy. rename. To(new File(newfname)) ; // Delete file fcopy. delete() ; // Clone file String src. Name = filepath + "wordtest. doc" ; String tar. Name = filepath + "wordtest_bak. doc" ; try { File. Input. Stream fis = new File. Input. Stream(new File(src. Name)); File. Output. Stream fos = new File. Output. Stream(new File(tar. Name)); int filesize = fis. available() ; byte[] buffer = new byte[1024] ; System. out. println(filesize + " bytes are copying");
while(true) { if(fis. available() < 1024) { int remain ; do { remain = fis. read() ; fos. write(remain); } while(remain != -1) ; break ; } else { fis. read(buffer) ; fos. write(buffer) ; } System. out. println(fis. available() + " bytes are left"); } fis. close() ; fos. close() ; } catch (Exception e) {} } }
存取UTF-8格式檔案 import java. io. Buffered. Reader; import java. io. File. Input. Stream; import java. io. Input. Stream. Reader; public class Read. File. Test { public static void main(String[] args) { String title = ""; int n = 0; double[] x = null; double[] y = null; File fin = new File("testdata_utf 8. txt"); if (f. exists()) { try { Buffered. Reader read = new Buffered. Reader( new Input. Stream. Reader( new File. Input. Stream(fin), “UTF-8”)); //讀取UTF 8格式檔案
read. skip(1); //避開檔頭字元 title = read. Line(); //讀取標題 n = Integer. parse. Int(read. Line()); //讀取資料數 x = new double[n]; y = new double[n]; for (int i = 0; i < n; i++) {//讀取數據資料格式如0, 100 -->用, 號分開 String str. Data = read. Line(); x[i] = Double. parse. Double(str. Data. split(", ")[0]); //x軸資料 y[i] = Double. parse. Double(str. Data. split(", ")[1]); //y軸資料 }//結束for迴圈 }//結束if判斷 } catch (Exception ex) { } //測試讀到的資料(如檔案不存在則輸出title預設值為空字串) System. out. println(title); for (int i = 0; i < n; i++) { System. out. println(x[i] + "t" + y[i]); } }
//寫入UTF-8格式檔案 File f = new File("testoutput_utf 8. txt"); try { Buffered. Writer out = new Buffered. Writer( new Output. Stream. Writer( new File. Output. Stream(f), “UTF-8")); out. write(str+"n"); out. close(); } catch(Exception ex) { } }
- Slides: 32