460 likes | 606 Views
語法入門 第一個 Java 程式 文字模式下與程式互動 資料、運算 流程控制. 第 3 章. 第一個 Java 程式. 定義類別( Class ) 定義區塊 ( Block ) 定義 main() 方法( Method ) 撰寫陳述( Statement ). public class HelloJava { public static void main(String[] args) { System.out.println(" 嗨!我的第一個 Java 程式! "); } }. Java 寫作風格. Class Name 請首字大寫
E N D
語法入門 第一個Java程式 文字模式下與程式互動 資料、運算 流程控制 第3章
第一個Java程式 • 定義類別(Class) • 定義區塊(Block) • 定義main()方法(Method) • 撰寫陳述(Statement) public class HelloJava{ public static void main(String[] args){ System.out.println("嗨!我的第一個Java程式!"); } }
Java寫作風格 • Class Name請首字大寫 • Variable Name和Method Name請首字小寫 • 如果名稱由數個英文字組成,第二個英文字以後首字大寫 • 內縮四個空格 • 註解部分如要變成說明文件,請遵照javadoc這個工具的寫作規則
Example • /** • * 第一行的兩個**用來告訴javadoc此部份註解要變成HTML文件的一部份 • * 這段註解裡的所有文字都會變成此類別一開頭的說明 • */ • public class Hello { // Class Name首字大寫 • /** • * 此段註解會變成描述main方法的一部分 • * @param argv 使用@param註記會產生參數(parameter)argv的相關說明 • * @return 傳回值的意義說明 • */ • public static void main(String[] argv) { // Method Name首字小寫 • // argv: array of references to String object • int myVariable; // 變數宣告 • int i, sum; • for (i = 1, sum = 0; i <= 100; i++) { • sum += i; • } • System.out.println("summation from 1 to 100 is "+sum); • } • }
給C使用者的第一個Java 程式 • 給了C使用者類似 printf() 的功能 public class HelloJavaForC { public static void main(String[] args) { System.out.printf("%s! 這是您的第一個Java程式!\n", "C語言Fan"); } } System.out.printf("%s! 這是您的第二個Java程式!", "C語言Fan").println(); System.out.printf("%s! 這是您的第 %d個Java程式!\n", "C語言Fan", 3);
為程式加入註解 • 原始碼檔案中被標註為註解的文字,編譯器不會去處理它 /* 作者:良葛格 * 功能:示範printf()方法 * 日期:2005/4/30 */ public class ThirdJavaForC { public static void main(String[] args) { // printf() 是J2SE 5.0的新功能,必須安裝JDK 5.0才能編譯 System.out.printf("%s! 這是您的第 %d 個Java程式!\n", "C語言Fan", 3); } }
為程式加入註解 • 不能用巢狀方式來撰寫多行註解 • 多行註解可以包括單行註解 /* 註解文字1……bla…bla /* 註解文字2……bla…bla */ */ /* 註解文字1……bla…bla // 註解文字2……bla…bla */
使用Scanner取得輸入 • 在 J2SE 5.0中,可以使用java.util.Scanner類別取得使用者的輸入 • 可以使用這個工具的next()功能,來取得使用者的輸入字串 Scanner scanner = new Scanner(System.in); System.out.print("請輸入您的名字:"); System.out.printf("哈囉! %s!\n", scanner.next()); System.out.print("請輸入一個數字: "); System.out.printf("您輸入了 %d !\n", scanner.nextInt());
使用 BufferedReader 取得輸入 • BufferedReader建構時接受java.io.Reader物件 • 可使用java.io.InputStreamReader BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(System.in)); System.out.print("請輸入一列文字,可包括空白: "); String text = bufferedReader.readLine(); System.out.println("您輸入的文字: " + text);
標準輸入輸出串流 • System類別中的靜態物件out • 提供標準輸出串流(Stream)輸出 • 通常對應至顯示輸出(終端機輸出) • 可以將輸出重新導向至一個檔案 • java HelloJava > HelloJavaResult.txt • System標準輸入串流in • 在程式開始之後它會自動開啟,對應至鍵盤或其它的輸入來源
標準輸入輸出串流 • 標準錯誤輸出串流err • 在程式執行後自動開啟,將指定的字串輸出至顯示裝置或其它指定的裝置 • err會立即顯示錯誤訊息 • err輸出串流的訊息不會被重新導向 System.out.println("使用out輸出訊息"); System.err.println("使用err輸出訊息"); java ErrDemo > ErrDemoResult.txt 使用err輸出訊息
輸出格式控制 System.out.println("\u0048\u0065\u006C\u006C\u006F");
輸出格式控制 • 若是使用J2SE 5.0或更高的版本 // 輸出 19 的十進位表示 System.out.printf("%d%n", 19); // 輸出 19 的八進位表示 System.out.printf("%o%n", 19); // 輸出 19 的十六進位表示 System.out.printf("%x%n", 19);
輸出格式控制 • 可以在輸出浮點數時指定精度 • System.out.printf("example:%.2f%n", 19.234); • example:19.23 • 可以指定輸出時,至少要預留的字元寬度 • System.out.printf("example:%6.2f%n", 19.234); • example: 19.23 • 補上一個空白在前端
基本的資料型態(Primitive type) • 整數 • 短整數(short)(佔2個位元組) • 整數(int)(佔4個位元組) • 長整數(long)(佔8個位元組) • 位元組 • 專門儲存位元資料 • 佔一個位元組 • 浮點數 • 浮點數(float)(佔4個位元組) • 倍精度浮點數(double)(佔8個位元組)
基本的資料型態(Primitive type) • 字元 • 採Unicode編碼 • 前128個字元編碼與ASCII編碼相容 • 每個字元資料型態佔兩個位元組 • 可儲存的字元範圍由'\u0000'到'\uFFFF' • 布林數 • 佔記憶體2個位元組 • 可儲存true與false兩個數值
基本的資料型態(Primitive type) System.out.printf("short \t數值範圍:%d ~ %d\n", Short.MAX_VALUE, Short.MIN_VALUE); System.out.printf("int \t數值範圍:%d ~ %d\n", Integer.MAX_VALUE, Integer.MIN_VALUE); System.out.printf("long \t數值範圍:%d ~ %d\n", Long.MAX_VALUE, Long.MIN_VALUE); System.out.printf("byte \t數值範圍:%d ~ %d\n", Byte.MAX_VALUE, Byte.MIN_VALUE); System.out.printf("float \t數值範圍:%e ~ %e\n", Float.MAX_VALUE, Float.MIN_VALUE); System.out.printf("double \t數值範圍:%e ~ %e\n", Double.MAX_VALUE, Double.MIN_VALUE);
變數、常數 • 在Java中要使用變數,必須先宣告變數名稱與資料型態 • 使用int、float、double、char等關鍵字來宣告變數名稱並指定其資料型態 • 不可以使用數字作為開頭 • 不可以使用一些特殊字元,像是*&^%之類 • 不可以與Java 內定的關鍵字同名 int age; // 宣告一個整數變數 double scope; // 宣告一個倍精度浮點數變數
變數、常數 • 鼓勵用清楚的名稱來表明變數的作用 • 不可以宣告變數後,而在未指定任何值給它之前就使用它 • 編譯器在編譯時會回報這個錯誤 int ageOfStudent; int ageOfTeacher; variable var might not have been initialized
變數、常數 • 使用「指定運算子」'='來指定變數的值 int ageOfStudent = 5; double scoreOfStudent = 80.0; char levelOfStudent = 'B'; System.out.println("年級\t 得分\t 等級"); System.out.printf("%4d\t %4.1f\t %4c", ageOfStudent, scoreOfStudent, levelOfStudent);
變數、常數 • 宣告變數名稱的同時,加上“final”關鍵字來限定 • 這個變數一但指定了值,就不可以再改變它的值 final int maxNum = 10; maxNum = 20; cannot assign a value to final variable maxNum
算術運算 • 加(+)、減(-)、乘(*)、除(/)、餘除運算子(%) • System.out.println(1 + 2 * 3); • System.out.println(1+2+3 / 4); • System.out.println((double)(1+2+3) / 4);
算術運算 • 這段程式會印出什麼結果? • 使用下面的方法 int testNumber = 10; System.out.println(testNumber / 3); int testNumber = 10; System.out.println(testNumber / 3.0); System.out.println((double) testNumber / 3);
算術運算 • 將精確度大的值指定給精確度小的變數時,由於在精確度上會有遺失,編譯器會認定這是一個錯誤 int testInteger = 0; double testDouble = 3.14; testInteger = testDouble; System.out.println(testInteger); possible loss of precision found : double required: int testInteger = testDouble ^ 1 error
算術運算 • 必須明確加上轉換的限定字,編譯器才不會回報錯誤 • '%'運算子是餘除運算子 testInteger = (int) testDouble; count = (count + 1) % 360;
比較、條件運算 • 大於(>)、不小於(>=)、小於(<)、不大於(<=)、等於(==)、不等於(!=) System.out.println("10 > 5 結果 " + (10 > 5)); System.out.println("10 >= 5 結果 " + (10 >= 5)); System.out.println("10 < 5 結果 " + (10 < 5)); System.out.println("10 <= 5 結果 " + (10 <= 5)); System.out.println("10 == 5 結果 " + (10 == 5)); System.out.println("10 != 5 結果 " + (10 != 5));
比較、條件運算 • 條件運算子 條件式 ? 成立傳回值 : 失敗傳回值 System.out.println("該生是否及格? " + (scoreOfStudent >= 60 ? '是' : '否')); System.out.println("是否為奇數? " + (number%2 != 0 ? '是' : '否'));
邏輯、位元運算 • 「且」(&&)、「或」(||)、「反相」(!) • &(AND)、|(OR)、^(XOR)與~(補數) int number = 75; System.out.println((number > 70 && number < 80)); System.out.println((number > 80 || number < 75)); System.out.println(!(number > 80 || number < 75)); System.out.println("0 AND 0\t\t" + (0 & 0)); System.out.println("0 AND 1\t\t" + (0 & 1)); System.out.println("1 AND 0\t\t" + (1 & 0)); System.out.println("1 AND 1\t\t" + (1 & 1)); byte number = 0; System.out.println((int)(~number));
邏輯、位元運算 • 左移(<<)、右移(>>)、>>>運算子 int number = 1; System.out.println( "2的0次: " + number); number = number << 1; System.out.println("2的1次: " + number); number = number << 1; System.out.println("2的2次: " + number); number = number << 1; System.out.println("2的3次:" + number); 00000001 1 00000010 2 00000100 4 00001000 8
遞增、遞減運算 • 遞增、遞減運算子 • 將遞增或遞減運算子撰寫在變數之前或變數之後 int i = 0; System.out.println(++i); System.out.println(--i); int i = 0; int number = 0; number = ++i; // 相當於i = i + 1; number = i; System.out.println(number); number = --i; // 相當於i = i - 1; number = i; System.out.println(number);
遞增、遞減運算 • 將遞增或遞減運算子撰寫在變數之前或變數之後 int i = 0; int number = 0; number = i++; // 相當於number = i; i = i + 1; System.out.println(number); number = i--; // 相當於 number = i; i = i - 1; System.out.println(number);
if 條件式 • 語法 • 複合陳述句 if(條件式) 陳述句一; else 陳述句二; if(條件式) { 陳述句一; 陳述句二; } else { 陳述句三; 陳述句四; }
if 條件式 Scanner scanner = new Scanner(System.in); System.out.print("請輸入數字: "); int input = scanner.nextInt(); int remain = input % 2; // 求除 2 的餘數 if(remain == 1) // 如果餘數為1 System.out.println(input + "為奇數"); else System.out.println(input + "為偶數");
if 條件式 • if 中再設定執行的條件 if(條件式一) { 陳述句一; if(條件式二) 陳述句二; 陳述句三; } if(條件式一) { 陳述句一; // 其它陳述句 } else if(條件式二) 陳述句二; if(條件式一) { 陳述句一; // 其它陳述句 } else if(條件式二) 陳述句二;
if 條件式 Scanner scanner = new Scanner(System.in); System.out.print("輸入分數:"); int score = scanner.nextInt(); if(score >= 90) System.out.println("得A"); else if(score >= 80 && score < 90) System.out.println("得B"); else if(score >= 70 && score < 80) System.out.println("得C"); else if(score >= 60 && score < 70) System.out.println("得D"); else System.out.println("得E(不及格)");
switch 條件式 • switch的語法架構 switch(變數名稱或運算式) { case 符合數字或字元: 陳述句一; break; case 符合數字或字元: 陳述句二; break; default: 陳述三; }
Scanner scanner = new Scanner(System.in); System.out.print("請輸入分數: "); int score = scanner.nextInt(); int level = (int) score/10; switch(level) { case 10: case 9: System.out.println("得A"); break; case 8: System.out.println("得B"); break; case 7: System.out.println("得C"); break; case 6: System.out.println("得D"); break; default: System.out.println("得E(不及格)");
for 迴圈 • 基本語法 for(初始式; 判斷式; 遞增式) {陳述句一; 陳述句二; } for(int j = 1; j < 10; j++) { for(int i = 2; i < 10; i++) { System.out.printf("%d*%d=%2d ",i, j, i * j); } System.out.println(); }
for 迴圈 • for括號中的每個陳述區塊是以分號 ';' 作區隔,而在一個陳述區塊中若想寫兩個以上的陳述句,則使用逗號 ',' 作區隔 for (int i = 2, j = 1; j < 10; i = (i==9)?((++j/j)+1):(i+1)) { System.out.printf("%d*%d=%2d%c", i, j, i * j, (i==9 ? '\n' : ' ')); }
while 迴圈 Scanner scanner = new Scanner(System.in); int score = 0; int sum = 0; int count = -1; while(score != -1) { count++; sum += score; System.out.print("輸入分數(-1結束):"); score = scanner.nextInt(); } System.out.println("平均:" + (double) sum/count)
while 迴圈 Scanner scanner = new Scanner(System.in); int input = 0; int replay = 0; do { System.out.print("輸入整數值:"); input = scanner.nextInt(); System.out.println("輸入數為奇數?" + ((input%2 == 1) ? 'Y': 'N')); System.out.print("繼續(1:繼續 0:結束)?"); replay = scanner.nextInt(); } while(replay == 1);
break、continue • break可以離開目前switch、for、while、do while的區塊 • continue只會結束其之後區塊的陳述句,並跳回迴圈區塊的開頭繼續下一個迴圈 for(int i = 1; i < 10; i++) { if(i == 5) break; System.out.println("i = " + i); } for(int i = 1; i < 10; i++) { if(i == 5) continue; System.out.println("i = " + i); }
break、continue • break與continue還可以配合標籤使用 back : { for(int i = 0; i < 10; i++) { if(i == 9) { System.out.println("break"); break back; } } System.out.println("test"); }
break、continue • break與continue還可以配合標籤使用 back1: for(int i = 0; i < 10; i++){ back2: for(int j = 0; j < 10; j++) { if(j == 9) { continue back1; } } System.out.println("test"); }