CS@KKU Java Summer Camp 2011 Day 1-2 •Variable, Type •Expressions and Flow Control Wachirawut Thamviset 1 จุดประสงค์ การเรียน สามารถใช้ หมายเหตุแบบต่างๆ ในภาษาจาวาได้ ทราบกฎเกณฑ์การตั้งชื่อ Identifier ทราบถึงชื่อที่เป็ น Keyword รู ้ความแตกต่างระหว่าง primitive type และ reference type 2 Primitive Types ใน Java จะมีชิดข้อมูลแบบ Primitive อยู่ 8 ชนิดได้แก่ ตรรก (Logical) - boolean (มีค่าเฉพาะ true หรื อ false) ตัวอักขระ (1 ตัว) - char (ASCII code และ Unicode) จานวนเต็ม - byte, short, int และ long ทศนิยม - double, float 3 Premitive Data Type Type boolean char byte short int long float double Size (bit) 1 16 8 16 32 64 32 64 Min Max true , false Unicode 0 Unicode 216-1 -128 127 -215 +215-1 -231 +231-1 -263 +263-1 ± ~ 10-44.85 ± ~ 10-38.53 ± ~10-323.3 ± ~10 308.3 4 Logical - boolean ตัวแปรแบบ boolean สามารถมีค่าได้ 2 สถานะคือ true และ false ตัวอย่างการประกาศ boolean flag = true; เราสามารถใช้คาสัง่ เปรี ยบเทียบเพื่อสร้างค่า boolean ก็ได้ เช่น boolean flag = 5 < 6; 5 Char ตัวอักษรของ Java จะมีขนาด 16 bit (Unicode) การกาหนดค่าจะอยูใ่ นเครื่ องหมายคาพูดเดียว ‘ ‘ รู ปแบบการใช้ ‘a’ ตัวอักษร a ‘\t’ หมายถึง tab ‘\u0E01 เป็ นรหัส unicode โดยใช้เลขฐาน 16 จานวน 4 ตัว ดังตัวอย่าง 0E01 แทน รหัสตัวอักษร ก.ไก่ 6 Java String ไม่ใช่ primitive type , แต่ string เป็ น class แทนค่าใช้เครื่ องหมาย คาพูดคู่ “ “ ตัวอย่างการใช้ String name = “John”; String text = “Hello !!\n John”; 7 การจัดการ String การจัดการทัง้ หมดจะทาผาน method ทีอ ่ ยูใน Object String ่ ่ เช่น trim() ตัด space ซ้ายขวาออก toUpperCase() แปลงเป็ นตัวใหญ่ toLowerCase() แปลงเป็ นตัวพิมพเล็ ์ ก toCharArray() แปลงเป็ น array ของตัวอักษร (เมทอดอืน ่ ๆ สามารถดูไดใน JDK Document ) ้ String s1 = “Hello”.toLowerCase(); String s2 = s1.toUpperCase(); s1 -> “hello” s2 -> “HELLO” 8 String เราไม่สามารถแก้ไขค่าของ String โดยตรง ถ้าต้องการเปลี่ยนค่าของ String ทาได้โดยสร้าง String ใหม่เท่านั้น เช่น String s = “Hello”; ถ้าต้องการเปลี่ยนให้เป็ นตัวอักษรใหญ่ตอ้ งใช้วิธี s = s.toUpperCase(); 9 Object to String ใน จาวาทุก Object จะมีเมทอดที่ชื่อว่า toString() ดังนั้นเราจึง สามารถแปลงข้อมูลของออบเจคต์ทุกชนิดเป็ น String ได้เช่น Font f = new Font("Arial",Font.BOLD,20); String fname = f.toString(); fname จะมีค่าเป็ นข้อความ java.awt.Font[family=Arial,name=Arial,style=bold,size=20] 10 การเชื่อม String String sx = 100 + 10.45; // ผิด String sy = 100+ 10.45+”$”; // 110.45$ String sz = “$”+100+ 10.45; // $10010.45 ถ้า String + กับนิพจน์ นิพนธ์น้ นั จะถูกแปลงให้เป็ น String ก่อนแล้วเชื่อมกัน 100+10.45+”$” => 110.45+”$” => “110.45”+”$” “$”+100+10.45 => “$”+”100”+10.45 => “$100”+”10.45” 11 เลขจานวนเต็ม มี 4 ระดับ byte short int long 8 bit 16 bit 32 bit 64 bit 12 เลขจานวนเต็ม มีการแทนค่าได้ 3 รู ปแบบ (ฐานสิ บ ฐานแปด และ ฐาน 16) 77 เลข 77 เป็ นเลขฐาน 10 077 เป็ นเลขฐาน 8 มีค่าเท่ากับ 63 ในฐาน 10 0x77 เป็ นเลขฐาน 16 มีค่าเท่ากับ 119 ในฐาน 10 ค่าปกติจะเป็ น integer เติมตัวอักษร L หรื อ l (แอลเล็ก) ต่อท้ายหมายถึงชนิด long 77L แนะนาให้ใช้ L เพราะ l(แอล) จะมีรูปร่ างเหมือนเลข 1(หนึ่ง) 13 ทศนิยม มี 2 ชนิดคือ float 32 bit double 64 bit 14 ทศนิยม การแทนค่า ใช้ E กาหนดค่า 10 ยกกาลัง ใช้ F ต่อท้ายหมายถึง float ใช้ D ต่อท้ายหมายถึง double (ถ้าไม่กาหนดจะเป็ น double) ตัวอย่าง 3.14 3.14E20 หมายถึง 3.14 x 1020 1.2E+30D หมายถึง 1.2 x 1030 1.2F หมายถึง 1.2 เป็ นแบบ float 15 Reference Type ตัวแปรในภาษาจาวาที่ไม่ใช่ Primitive Type จะเป็ น Reference Type ใช้จดั การกับ Object เช่น Foo a = new Foo(10); Foo b = a; // ให้ b อ้างถึง object เดียวกับ a a.setX(20); หรื อ b.setX(20) จะมีผลเหมือนกัน เพราะว่า ทั้ง a และ b อ้างถึง Object เดียวกัน 16 The this Reference การใช้คา this เพื่ออ้างถึงสมาชิกของ Class ที่อยูใ่ นตาแหน่งที่เขียนคาสัง่ ใช้เพื่ออ้างตัวแปรเมื่อ มีตวั แปรที่มีชื่อซ้ ากัน เช่น class Foo{ this.x int x; void setX(int x){ this.x = x; } } 17 Identifiers หมายถึง ชื่อ ที่ใช้ต้ งั ชื่อตัวแปร,class หรื อ method สามารถเริ่ มต้นด้วยเครื่ องหมาย _ หรื อ $ สามารถตั้งชื่อด้วยตัวอักษร Unicode เป็ น Case-Sensitive และ ไม่จากัดความยาว ตัวอย่าง example , username , UserName, FirstName, $money 18 Identifiers คุณสามารถตั้งชื่อ Class,ตัวแปร และ method ด้วยภาษาไทยได้ แต่ไม่ควรใช้ภาษาไทยตั้งชื่อ Class เพราะจะทาให้ไม่สามารถใช้ บน OS ที่ไม่สนับสนุนภาษาไทย การตั้งชื่อ Class ควรขึ้นต้นด้วยตัวอักษรใหญ่ ชื่อ Method และ ตัวแปร ควรขึ้นต้นด้วยอักษรเล็ก Identifiers ไม่สามารถตั้งชื่อเหมือนกับ Keyword ของจาวาได้ 19 Identifier ไม่สามารถใช้สญ ั ลักษณ์พิเศษอื่น เช่น +, -, *, &, %, # ฯลฯ เป็ นส่ วนประกอบอยูภ่ ายในชื่อได้ สามารถตั้ง Identifier ให้มีความยาวเท่าใดก็ได้ การตั้ง Identifier จะมีลกั ษณะเป็ น Case Sensitive เช่น MyClass, myClass, MYCLASS และ myclass ต่างก็เป็ น Identifier ที่แตกต่างกัน ไม่ใช่ตวั เดียวกัน 20 Java Keywords เป็ นคาเฉพาะ ที่ถูกสงวนไว้ใช้ในภาษา Java สาหรับใช้นิยามคลาส และ สร้างคาสัง่ เช่น abstract , assert, boolean,break,continue class,const, if , else this, super, public, private ไม่สามารถใช้ต้ งั ชื่อ Indentifier ได้ 21 Java Keywords ไม่ สามารถใช้ ตั้งเป็ น Identifier ได้ ตัวอย่ างเช่ น abstract,boolean,break, byte, case, catch, char, class,const, continue, default, delegate, do, double, else, extends,false, final, finally, float, for, goto, if, implements, import,instance, of, int, interface, long, multicast, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, void, volatile, while 22 Scoping ใช้เครือ ่ งหมาย { } กาหนด Scope ตัวแปรจะใช้ไดเฉพาะในช ่ รางมั น ้ ่ วงโปรแกรมทีส ้ เทานั ่ ้น { มีตวั แปร I,G int I = 100; { มีตวั แปร int G = I+10; } System.out.printf(“%d %d”, I , G ); I แตตั ่ วแปร G จะหายไป } Scope จะเป็ นตัวบอกอายุของตัวแปร เมื่อออกนอก Scope มันก็จะถูกทาลาย 23 Expressions and Flow Control 24 Operator In addition to the simple operators in JAVA addition(+) subtraction(-) multiplication(*) division(/) modulus(%) There are many others. 25 Increment and Decrement Operators: ้ ม ++ ใชเพิ ่ ค่าตัวแปรขึน ้ 1 ้ -- ใชลดค่ าตัวแปรลง 1 int aNumber = 8; aNumber = aNumber + 1; aNumber++; aNumber = aNumber – 1; aNumber -- ; 26 Increment and Decrement Operators: ้ ม ++ ใชเพิ ่ ค่าตัวแปรขึน ้ 1 ้ -- ใชลดค่ าตัวแปรลง 1 int aNumber = 8; aNumber = aNumber + 1; aNumber++; aNumber = aNumber – 1; aNumber -- ; สงิ่ ทีแ ่ ตกต่างระหว่าง i++; และ ++i; int x=5,y=5; System.out.println(x++); 5 System.out.println(++y); 6 27 Logical Operators: JAVA allows for standard comparison between numbers: < less than 5<7 //returns true 23.321 >= 54.1 //returns false <= less than or equal to 'g' != 'G' //returns true 'g' == 'g' //returns true == equal to != not equal to >= greater than or equal to > greater than จะได้ ผลลัพธ์ เป็ น true หรือ false 28 Logical Operators: Operator ทีใ่ ช้ จัดการกับข้ อมูลแบบ boolean ได้ แก่ ! not (prefix) && conditional and !(5 < 7) ('a' == 'a') && (5 < 7) ('G' == 'a') && (5 < 7) || conditional or ('G' == 'a') || (5 < 7) ('G' == 'a') || (5 >= 7) //returns false //returns true //returns false //returns true //returns false การคานวณ จากซ้ายไปขวา สาหรับ && ถ้ามีเงื่อนไขใดเป็ น false ก็จะไม่จาเป็ นตรวจสอบเงื่อนไขถัดไป สาหรับ || ถ้าพบเงื่อนไขที่เป็ น true ก็จะไม่ตอ้ งตรวจสอบเงื่อนไขถัดไป 29 Bitwise Operators: JAVA also provides bitwise operators for integers and booleans: ~ bitwise complement (prefix unary operator) & bitwise and | bitwise or ^ bitwise exclusive-or << shift bits left, filling in with zeros >> shift bits right, filling in with sign bit >>> shift bits right, filling in with zeros 30 Assignment Operators: ใช้คานวณและกาหนดค่าให้ตวั แปร มีรูปแบบดังนี้ variable <op>= expression; ตัวอย่าง x = x+ 6; สามารถเขียนใหม่เป็ น x += 6; y = y * 2; สามารถเขียนใหม่เป็ น y *= 2; 31 Operator Precedence ลาดับการคานวณ operator สามารถควบคุมด้วย วงเล็บ ( ) 30 + 5 * 2 - 18 / 2 - 2 30 + 10 – 18 / 2 – 2 30 + 10 – 9 – 2 40 – 9 – 2 31 – 2 29 32 ตารางแสดงลาดับของ operator postfix operators [] . (<exp>) <exp>++ prefix operators ++<exp> <exp> creation/cast new (<type>)<exp> multiplication/division/ modulus * / addition/subtraction + - shift << comparison < equality == bitwise-and & --<exp> ~<exp> <exp>-- !<exp> % >> <= >>> > >= instanceof != 33 ตารางแสดงลาดับของ operator (ต่ อ) bitwise-xor ^ bitwise-or | logical and && logical or || conditional <bool_exp>? <true_val>: <false_val> assignment = operation assignment += bitwise assignment >>= boolean assignment &= -= *= <<= ^= /= %= >>>= |= 34 Math Functions There is a whole library of math functions that can be used on numbers. Here are just a few on the common ones: Trigonometric: Math.sin(0) Math.cos(0) Math.tan(0.5) //returns 0.0 which is a double //returns 1.0 //returns 0.5463024898437905 35 Math Functions (ต่ อ) Conversion and Rounding: Math.round(6.6) //returns 7 Math.round(6.3) //returns 6 Math.ceil(9.2) //returns 10 Math.ceil(-9.8) //returns -9 Math.floor(9.2) //returns 9 Math.floor(-9.8) //returns -10 36 Math Functions (ต่ อ) Powers and Exponents: Math.sqrt(144) //returns 12.0 Math.pow(5,2) //returns 25.0 Math.exp(2) //returns 7.38905609893065 Math.log(7.38905609893065) //returns 2.0 37 Math Functions (ต่ อ) Powers and Exponents: Math.sqrt(144) //returns 12.0 Math.pow(5,2) //returns 25.0 Math.exp(2) //returns 7.38905609893065 Math.log(7.38905609893065) //returns 2.0 38 Math Functions (ต่ อ) Comparison: Math.max(560, 289) //returns 560 Math.min(560, 289) //returns 289 Generation of a Random Number: Math.random() //returns a double >=0.0 and <1.0 39 Math Functions (ต่ อ) ต ัวอย่าง: เราจะสามารถคานวณจุดทศนิยม 2 หล ักได้อย่างไร 5415.23491872773773 => 5415.24 วิธก ี ารอย่างง่าย คูณด้วย 100 แล้ว round จากนน ั้ หารด้วย 100 double x = 524.14982232132143; System.out.println("x is: " + x); x = Math.round(x * 100) / 100.0; System.out.println("x rounded is: " + x); 40 Flow Control Every programming language must have the ability to: evaluate code in some specific order evaluate different code depending on some condition repeat a selected portion of code a specific number or times, or until some condition occurs 41 Control Structure sequence executing code line-by-line. selection being able to choose as to whether or not a piece of code is to be executed based on some condition. repetition executing the same code fragment more than once. 42 Control Structure if switch for while The control structures will be used to handle the selection and repetition. 43 The if control structure ใช้ควบคุมการตัดสิ นใจ if (<boolean-expression>) { //statements for true case; } if (<boolean-expression>) { //statements for true case; } else { //statements for false case; } 44 ตัวอย่ าง สร้างฟังก์ชนั คานวณความชัน ระหว่างจุด 2 จุด public static double slope(int x1, int x2, int y1, int y2) { if (x1 == x2) return Double.NaN; return ((y2- y1) / (x2 - x1)); } หมายเหตุ Double.NaN เป็ นค่าคงที่ สาหรับกาหนดว่า หาค่าไม่ได ้ 45 ตัวอย่ าง การแสดงผลสามารถใช้ if เพื่อเลือกวิธีการแสดงได้ double slope = slope(1,1,1,4); if (Double.isNaN(slope)) System.out.println("Slope is undefined"); else System.out.println("Slope is " + slope); ้ หมายเหตุ Double.isNaN ใชทดสอบ ตัวเลขทีห ่ าค่าไม่ได ้ 46 ตัวอย่ าง : if public class PollutionClassifier { public static String classify(int polutionIndex) { if ((polutionIndex < 0) || (polutionIndex > 100)) return null; if ((polutionIndex >= 0) && (polutionIndex <= 34)) return "Pleasant"; if ((polutionIndex >= 35) && (polutionIndex <= 60)) return "Unpleasant"; if (polutionIndex > 60) (ระดับมลภาวะ) return "Hazardous"; return null; } } 47 ตัวอย่ าง : if (ระดับมลภาวะ) ลดความซับซ้ อน public static String classify(int polutionIndex) { if ((polutionIndex < 0) || (polutionIndex > 100)) return null; else if (polutionIndex <= 34) return "Pleasant"; else if (polutionIndex <= 60) return "Unpleasant"; else return "Hazardous"; } 48 ตัวอย่ าง : if (ระดับมลภาวะ) ลดความซับซ้ อน ในความเป็ นจริง การใชค้ าสงั่ return ไม่จาเป็ นต ้องมี else ก็ได ้ public class PollutionClassifier { public static String classify(int polutionIndex) { if ((polutionIndex < 0) || (polutionIndex > 100)) return null; if (polutionIndex <= 34) return "Pleasant"; if (polutionIndex <= 60) return "Unpleasant"; return "Hazardous"; } } 49 The switch Statement ใช้สร้างสาหรับเงื่อนไขที่มีหลาย ทางเลือก switch (<switch-expression>) { case value1: statements for case1; break; case value2: statements for case2; break; ... case valueN: statements for caseN; break; default: statements for default case; break; } ้ ้เฉพาะ expression ทีเ่ ป็ น premitive type ข ้อจากัด : ใชได 50 The switch Statement : ตัวอย่ าง ใช้ สร้ างสาหรับเงือ่ นไขทีม่ หี ลายทางเลือก public class Grader { public static void printGradeRangeFor(char aLetter) { switch(aLetter) case 'A': System.out.println("80% - 100%"); break; case 'B': System.out.println("70% - 79%"); break; case 'C': System.out.println("60% - 69%"); break; case 'D': System.out.println("50% - 59%"); break; case 'F': System.out.println("0% - 49%"); break; default: System.out.println("not defined"); } } } 51 The switch Statement : ตัวอย่ าง ปัญหาจานวนวันในเดือน version 1 public static int daysInMonth(int month) { if ((month == 1) || (month == 3) || (month == 5) || (month == 7) | (month == 8) || (month == 10) || (month == 12)) return 31; if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) return 30; if (month == 2) return 28; } 52 The switch Statement : ตัวอย่ าง ปัญหาจานวนวันในเดือน version 2 ปรับปรุงลาดับเงือ่ นไข เพือ่ ลงความซับซ้ อน public static int daysInMonth(int month) { if (month == 2) return 28; if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) return 30; return 31; } 53 The switch Statement : ตัวอย่ าง ปัญหาจานวนวันในเดือน ใช้ switch version 3 public static int daysInMonth(int month) { int days; switch(month) { case 2: days = 28; break; case 4: case 6: case 9: case 11: days = 30; break; default: days = 31; } return days; } 54 ตัวอย่ างที่ผดิ switch (age) { case 1-12: price = 5.00; break; case 13-17: price = 8.00; break; case 18-54: price = 10.00; break; default: price = 6.00; } switch (name) { case "Mark": bonus = 3; break; case "Betty": bonus = 2; break; case "Jane": bonus = 1; break; default: bonus = 0; } 55 The for Loop ใช้เพื่อควบคุมการทาซ้ า ถ้ าต้ องการแสดงข้ อความต่ อไปนี้ ********** ********** ********** ********** ********** จะเขียนโปรแกรมแบบนี้ ? System.out.println("**********"); System.out.println("**********"); System.out.println("**********"); System.out.println("**********"); System.out.println("**********"); 56 The for Loop ไวยกรณ์ for (<start-expression>; <check-expression>, <update-expression>) { // body of the loop; } <start-expression> เป็ น expression เริม ่ ต ้นการวนลูป ปกติจะใชตั้ ง้ ค่าเริม ่ ต ้นของตัวแปร <check-expression> เป็ นเงือ ่ นไขการวนลูป การทางานจะออกจากลูปเมือ ่ เงือ ่ นไขเป็ นเท็จ <update-expression> เป็ นคาสงั่ สาหรับปรับปรุงตัวแปร เมือ ่ วนรอบการทางานแต่ละรอบ 57 The for Loop เพือ ่ แก ้ปั ญหาทีน ่ าเสนอไว ้ตอนแรก เราสามารถใช ้ for ในการทา loop: for (int i=1; i<=5; i++) System.out.println("**********"); ถ ้าต ้องการให ้ทา 10 แถว ก็เปลีย ่ นแค่ 5 เป็ น 10: for (int i=1; i<=10; i++) System.out.println("**********"); 58 The for Loop ข้อควรระวัง เครื่ องหมาย ; หมายถึงคาสัง่ เปล่า ที่ไม่ทางานอะไร for (i=0;i<100;i++); { System.out.println(“***************”); } ระวังอย่างใส่ ; หลัง for 59 The while Loop ไวยกรณ์ while (<boolean-expression>) { //body of the loop; } จะวนลูป ทาคาสั่งที่อยูใ่ นปี กกา วนรอบไปเรื่ อย ๆ เมื่อเงื่อนไขเป็ นจริ ง 60 The while Loop ตัวอย่าง int i=0; while (i<=10) { System.out.println(“***************”); i++; } 61 The while Loop ตัวอย่าง int i=0; do { System.out.println(“***************”); i++; } while (i<=10); 62 การใช้ break, continue break ใช้เพื่อจบการวนลูป continue ใช้เพื่อข้ามการทางานในลูปปัจจุบนั ไปทาในรอบต่อไป int i=0; while(i<=100) { System.out.println(i); if(i % 5 == 0) { i++; continue; } i++; } 63 รู ปแบบการเขียน Code ภาษา Java Packages package app.lab; Classes class BallFrame Interfaces interface AniObj Method void moveObj( ); 64 รู ปแบบการเขียน Code ภาษา Java Variables int x; String currentStudent; Constants static int MAX_SIZE=10; Block for(int i=0;i<10;i++){ /// คาสัง่ } 65