59
1 พื้นฐานในภาษา Java

Computer Programming 2.2

Embed Size (px)

Citation preview

Page 1: Computer Programming 2.2

1

พนฐานในภาษา Java

Page 2: Computer Programming 2.2

2

ขอมลพนฐาน (Primitive Data Type)

Page 3: Computer Programming 2.2

3

Page 4: Computer Programming 2.2

4

ตวแปร (Variable)

การตงช อต วแปร (Identif iers) ควรมความหมาย ไมมชองวางและเครองหมาย เชน ? ! @ # % ^ & * ( ) [ ] { } . , ; : “ ‘ / และ \ ตวแรกของชอตวแปรควรเปนตวอกษรตวพมพเลก (a-z, _ หรอ $ ) หามใชคำาศพทสงวน เชน name, void, class, float ฯลฯ ตวพมพใหญ/เลก มความหมายตางกน ไมควรใชตวพมพใหญทกตว เพราะอาจเชอมโยงกบภาษาอนไมได

Page 5: Computer Programming 2.2

5

การประกาศตวแปร [<access_specif ier>] [<modif ier>] <data_type> <variable_name1>

[ ,

<variable_name2>] . . . ; public ใช น ยามตวแปรเพ อให น ำาไปใชก บ Class หรอโปรแกรมอนได private ใช น ยามตวแปรเพ อให ใช ได เฉพาะใน Class ท สร างต วแปรหร อ Method น นข นมา protected ใช น ยามตวแปรเพ อให ใช ได เฉพาะ Class ท สร างข นมาด วยว ธ การส บทอด (Inheritance) โดยปกตใช ก บ Base Class static ใช น ยามตวแปรทต องการใหใช งานไดก บท ก Method ใน Class

f inal ใชน ยามตวแปรทต องการใชเก บข อม ลค าคงท (Constant) ซ งไม สามารถเปล ยนค าได

Page 6: Computer Programming 2.2

6

การกำาหนดคาใหกบต วแปร [<access_specif ier>] [<modif ier>] <data_type>

<variable_name1> = <value> [, <variable_name2> = <value>].. . ;

หรอ [<access_specif ier>] [<modif ier>] <data_type>

<variable_name>; <variable_name> = <value>;

การกำาหนดคาจ ำานวนเต ม int r = 1, b = 1, g = 1; long i2 = 300 * 30; private int employeeid = 0;

int salary; salary = 5000; int a = 024, b = 036; int data_c = 0x1D, data_d = 0x36;

Page 7: Computer Programming 2.2

7

การกำาหนดคาจ ำานวนจร ง f loat d1 = 34.0 - 0.1;double d2 = 1.0/2.0;stat ic f inal f loat PI = 3.141159; private f loat salary = 0.0F;stat ic f inal f loat TAX_RATE = .0725F;

การกำาหนดคาตรรกะ boolean done =true;

Page 8: Computer Programming 2.2

8

public class TestCalc{ public static void main(String[] args)

{ final double BOTTLE_VOLUME = 2.5; final double CAN_VOLUME = 0.35; int bottles = 4; int cans = 10; double total = (bottles * BOTTLE_VOLUME) + (cans * CAN_VOLUME); System.out.println("Total Volume is " + total); } }

Page 9: Computer Programming 2.2

9

การกำาหนดคาต วอ กษร ตองอยในสญลกษณหยาดฝน (Single Quote)

Page 10: Computer Programming 2.2

10

Page 11: Computer Programming 2.2

11

String String message = “Welcome”; Str ing firstName = “Sippakorn”, lastName =

“Saengthong”; private String name; private String name = “ ”; Str ing name1, name2;

name1 = “Tanisorn”; name2 = name1; การหาความยาวของ Stringint n = fname.length();

การดงข อความบางส วนทเกบในตวแปรแบบ String String fname = “Samphan”;Str ing sub = fname.substring (0,4); Str ing sub = fname.substring (1);

การเช อมต อข อความ String s1 = “Chantana”

Str ing s2 = “Promsiri” Str ing name1 = s1 + s2;

Page 12: Computer Programming 2.2

12

class test { public static void main(String[] args)

{ String fname = "Chutimond";int n = fname.length();System.out.println("Length of name = " + n);String a = fname.substring(0,1);System.out.println("First character of name = " + a);String lname = "Bunmark";String b = lname.substring(2-1,4);System.out.println("3 char. of lname from position 2 = " + b);int m = lname.length();String c = lname.substring(m-1,m);System.out.println("Last character of surname = " + c); } }

Page 13: Computer Programming 2.2

13

Page 14: Computer Programming 2.2

14

Page 15: Computer Programming 2.2

15

Page 16: Computer Programming 2.2

16

ตวดำำเนนกำร (Operator) Arithmetic Operators

Integer Arithmetic Operators : +, -, *, / และ %Floating-point Arithmetic Operators : +, -, *, / และ % Arithmetic Assignment Operators : +=, -=, *=, /= และ %= Increment and Decrement Arithmetic Operators : ++x, x++, - -x และ x- -

หมำยเหต 1. ( ) 2. ++, -- 3.  *, /, % 4. +, -

5. +=, -=, *=, /=, %= Assignment Operators

ตวอยำงเชน x = (y = y + 1) + 1;

Page 17: Computer Programming 2.2

17

// Integer Arithmetic Operators public class IntArithOper{ public static void main(String[ ] args)

{ System.out.println("Integer Arithmetic Operators ");System.out.println("1 + 2 = " + (1 + 2));System.out.println("1 - 2 = " + (1 - 2));System.out.println("1 * 2 = " + 1 * 2);System.out.println("1 / 2 = " + 1 / 2);System.out.println("1 % 2 = " + 1 % 2); } }

Page 18: Computer Programming 2.2

18

// Floating Arithmetic Operatorspublic class FloatArithOper{ public static void main(String[ ] args) { System.out.println("Floating Arithmetic Operators "); System.out.println("1.0 + 2.0 = " +(1.0 + 2.0));

System.out.println("1.0 - 2.0 = " +(1.0 - 2.0)); System.out.println("1.0 * 2.0 = " +1.0 * 2.0); System.out.println("1.0 / 2.0 = " +1.0 / 2.0); System.out.println("1.0 % 2.0 = " +1.0 % 2.0); } }

Page 19: Computer Programming 2.2

19

// Arithmetic Assignment Operators : Integerpublic class IntArithAssOper{ public static void main(String[ ] args)

{ int x = 1; System.out.println("Arithmetic Assignment Operators : Integer");x += 2; System.out.println("x += 2 is " + x);x -= 2; System.out.println("x -= 2 is " + x);x *= 2; System.out.println("x *= 2 is " + x);x /= 2; System.out.println("x /= 2 is " + x);x %= 2; System.out.println("x %= 2 is " + x); } }

Page 20: Computer Programming 2.2

20

// Arithmetic Assignment Operators : Floatpublic class FloatArithAssOper{ public static void main(String[ ] args) { float y =1f; System.out.println("Arithmetic Assignment Operators : Float"); y += 2; System.out.println("y += 2 is " + y); y -= 2; System.out.println("y -= 2 is " + y); y *= 2; System.out.println("y *= 2 is " + y); y /= 2; System.out.println("y /= 2 is " + y); y %= 2; System.out.println("y %= 2 is " + y); } }

Page 21: Computer Programming 2.2

21

//Increment and Decrement Operators public class TestIncDecOper{ public static void main(String[ ] args) { int a, b, x = 1, y = 1; a = x++; b = ++y; System.out.println("x = 1 , y = 1"); System.out.println("a = x++ , b = ++y"); System.out.println("x+ = " + x+" , +y = " +y); System.out.println("a+ = " + a+", +b = " +b); } }

Page 22: Computer Programming 2.2

22

//Assignment Operators public class TestAssOper{ public static void main(String[ ] args)

{ int x, y;x = y = 1;System.out.println("x = y = 1");System.out.println("x = "+ x + ", y = " + y);x = (y = y + 1) + 1;System.out.println("x = (y = y + 1) + 1");System.out.println("x = "+ x + ", y = " + y); } }

Page 23: Computer Programming 2.2

23

Bitwise OperatorsBoolean Bitwise Operators

~ (Bitwise Unary Not) & (Bitwise And) | (Bitwise Or) ^ (Bitwise Exclusive Or) >> (Shift Right) << (Shift Left) >>> (Shift Right Zero Fill)

Assignment Bitwise Operators &= (Bitwise And Assignment) |= (Bitwise Or Assignment) ^= (Bitwise Exclusive Or Assignment) >>= (Shift Right Assignment) <<= (Shift Left Assignment) >>>= (Shift Right Zero Fill Assignment)

Page 24: Computer Programming 2.2

24

//Bitwise Operators public class TestBitwiseOper{ public static void main(String[ ] args)

{ int A = 6, B = 7; System.out.println("A = " + Integer.toBinaryString(A)); System.out.println("B = " + Integer.toBinaryString(B)); System.out.println("~A = " + Integer.toBinaryString(~A)); System.out.println("A & B = " + Integer.toBinaryString(A&B)); System.out.println("A | B = " + Integer.toBinaryString(A|B)); System.out.println("A ^ B = " + Integer.toBinaryString(A^B)); System.out.println("A << 1 = " + Integer.toBinaryString(A<<1)); System.out.println("A >> 1 = " + Integer.toBinaryString(A>>1)); System.out.println("A >>> 1 = " + Integer.toBinaryString(A>>>1));} }

Page 25: Computer Programming 2.2

25

Relational Operators== Equal To != Not Equal To> Greater Than < Less Than

>= Greater Than or Equal To <= Less Than or Equal To

Logical Operators Boolean Logical Operators

& Logical And | Logical Or^ Logical Exclusive Or ! Logical Unary Not

Short-Circuit Logical Operators      && Short-Circuit And || Short-Circuit Or

Assignment Logical Operators      &= And Assignment |= Or Assignment ^= Exclusive Or Assignment

Page 26: Computer Programming 2.2

26

//Relational Operatorpublic class TestRelationalOper { public static void main(String args[])

{ boolean a = true, b = false;System.out.println(" a = " + a);System.out.println(" b = " + b);System.out.println(" a & b = " + (a & b));System.out.println(" a | b = " + (a | b));System.out.println(" a ^ b = " + (a ^ b));System.out.println(" !a = " + (!a)); } }

Page 27: Computer Programming 2.2

27

// Logical Operator ใชสำำหรบ Operands ทมชนดเปน boolean เทำนนpublic class TestBooleanLogicalOper { public static void main(String args[])

{ boolean a = true, b = false;System.out.println("a = true : a = " + a);System.out.println("b = false : b = " + b);System.out.println();

// กลมท 1 Boolean Logical OperatorsSystem.out.println("1. Boolean Logical Operators");

// Logical AndSystem.out.println("Logical And => a & b = " + (a & b));

// Logical OrSystem.out.println("Logical Or => a | b = " + (a | b));

// Logical Exclusive OrSystem.out.println("Logical Exclusive Or => a ^ b = " + (a ^ b));

// Logical Unary NotSystem.out.println("Logical Unary Not => !a = " + (!a));System.out.println();

} }

Page 28: Computer Programming 2.2

28

public class TestShortandAssLogicalOper { public static void main(String args[])

{ boolean a = true, b = false;System.out.println("a = true : a = " + a);System.out.println("b = false : b = " + b);System.out.println();

// กลมท 2 Short-Circuit Logical OperatorsSystem.out.println("2. Short-Circuit Logical Operators");

// Short-Circuit AndSystem.out.println("Short-Circuit And => a && b = " + (a && b));

// Short-Circuit OrSystem.out.println("Short-Circuit Or => a || b = " + (a || b));System.out.println();

// กลมท 3 Assignment Logical OperatorsSystem.out.println("3. Assignment Logical Operators");

// And AssignmentSystem.out.println("And Assignment => a &= b = " + (a &= b));

// Or AssignmentSystem.out.println("Or Assignment => a |= b = " + (a |= b));

// Exclusive Or AssignmentSystem.out.println("Exclusive Or Assignment => a ^= b = " + (a ^= b)); } }

Page 29: Computer Programming 2.2

29

Conditional Operators (<condition>) ? <expression 1> : <expression 2>

//Conditional Operatorpublic class TestCondOper { public static void main(String args[])

{ int x = Integer.parseInt(args[0]);int y = Integer.parseInt(args[1]);

//input x = 5, y = 3System.out.println((x > y)? x : y); } }

Page 30: Computer Programming 2.2

30

ลำำดบในกำรประมวลผลของ Operator

ล ำำด บ Operator ประเภท Assoc.

1 ()2 ++ (Increment), -- (Decrement)

!~ (Complement)(type_cast)

กำรคำำนวณbooleanintegerทกรปแบบ

RRRR

3 *, /, % กำรคำำนวณ L4 +, - กำรคำำนวณ L5 << (Left shift), >> (Right shift),

>>> (Zero fill)จำำนวนเตม L

6 <, <=, >, >=, Instanceof() กำรเปรยบเทยบ object

L

7 ==, != ขอมลพนฐำนและ object

L

Page 31: Computer Programming 2.2

31

ลำำด บ Operator ประเภท Assoc.

8 & (Bitwise AND) จำำนวนเตม L

9 ^ (Bitwise XOR) จำำนวนเตม L

10 | (Bitwise OR) จำำนวนเตม L11 && (AND) boolean L

12 || (OR) boolean L

13 ?: boolean R

14 =, *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=,^=, !=

อน ๆ R

Page 32: Computer Programming 2.2

32

ใหประมวลผลหำคำของนพจนa * b – c != a / b – c && --a > b++ || b % --c > 0

1. Increment และ Decrement Operator2. ตวกระทำำทำงคณตศำสตร *, /, %3. ตวกระทำำทำงคณตศำสตร - 4. Relational Operator5. ไมเทำกน6. &&7. ||

1 1 12 2 2

3 3 4 45

67

Page 33: Computer Programming 2.2

33

กำรแปลงชนดของตวแปร (Type Conversion)

1.กำรแปลงชนดขอมลโดยอตโนมต (Implicit) กรณทนพจนประกอบดวยตวแปรหลำยชนด Java จะตรวจสอบ

ชนด ขอมลของตวแปรในนพจน แลวเปลยนชนดขอมลใหเปนแบบทใชเนอทในหนวยควำมจำำมำกทสด โดยจะแปลงชนดขอมลโดยอตโนมต เมอชนดขอมลของตวแปรสำมำรถใชรวมกนได และตวแปรปลำยทำงมขนำดใหญกวำหรอเทำกบตวแปรตนทำง

2.กำรแปลงชนดขอมลแบบ Explicit หรอ Type Casting เปนกำรประกำศเปลยนแปลงประเภทของขอมลโดยผใชเอง

(target_type) expression;

Page 34: Computer Programming 2.2

34

3. กำรแปลงชนดขอมลโดยใช Type Wrapper เปนกำรสรำง Object ขนมำกอนทจะเรยก Method มำใชงำน public double doubleValue() public float floatValue() public int intValue() public long longValue() public String toString()

Page 35: Computer Programming 2.2

35

// Type Conversion : Implicitpublic class TestImplicit{ public static void main(String args[ ])

{ int a = 15/5;System.out.println("int a = 15/5 => " + a);

// method ชอ toBinaryString จำก Class ชอ Integer เปลยนขอมล Integer ใหอยในรป Binary

System.out.println("a = " + Integer.toBinaryString(a));System.out.println();

// int b = (15/5)*(float)2;float b = a * (float) 2;

// byte c = c*2;byte c = 5;System.out.println("float b = a * (float) 2 => " + b);System.out.println("byte c = 5");System.out.println("b/c => " + b/c);

Page 36: Computer Programming 2.2

36

/* method ชอ floatToIntBits จำก Class ชอ Float เปลยนขอมล Float ใหอยในรป Bit ของจำำนวนเตมแบบ Integer */

System.out.println("Integer.toBinaryString(Float.floatToIntBits(b/c))");System.out.println(Integer.toBinaryString(Float.floatToIntBits(b/c)));System.out.println();double d = 10.0d;System.out.println("double d = 10.0d");System.out.println("(b+c)/d => " + (b+c)/d);

/* method ชอ doubleToLongBits จำก Class ชอ Double เปลยนขอมล Double ใหอยในรป Bit ของจำำนวนเตมแบบ Long

method ชอ toBinaryString จำก Class ชอ Long เปลยนขอมล Long ใหอยในรป Binary */System.out.println("Long.toBinaryString(Double.doubleToLongBits((b+c)/d))");System.out.println(Long.toBinaryString(Double.doubleToLongBits((b+c)/d))); }}

Page 37: Computer Programming 2.2

37

// Type Conversion : Explicit หรอ Type Castingpublic class TestExplicit{ public static void main(String[ ] args)

{ char A = '0';int B = 2;System.out.println("char A = '0' => "+(int)A);System.out.println("int B = 2");System.out.println("(int) (A/B) => " + (int) (A/B)); } }

Page 38: Computer Programming 2.2

38

/* Type Conversion : Type Wrapper เปนกำรสรำง Object ขนมำกอนจะเรยก Method มำใชงำน*/public class TestTypeWrapper{ public static void main(String[ ] args)

{ String var1 = "25.75";Double d1 = Double.valueOf(var1);System.out.println("String var1 = 25.75");System.out.println("Double d1 = Double.valueOf(var1)");System.out.println("d1 => " + d1);double d2 = d1.doubleValue();System.out.println("double d2 = d1.doubleValue();");System.out.println("d2 => " + d2);System.out.println();

Page 39: Computer Programming 2.2

39

String var2 = "500";Integer int1 = Integer.valueOf(var2);System.out.println("String var2 = 500");System.out.println("Integer int1 = Integer.valueOf(var2)");System.out.println("int 1 => " + int1);int int2 = int1.intValue();System.out.println("int int2 = int1.intValue()");System.out.println("int 2 => " + int2); } }

Page 40: Computer Programming 2.2

40

public class TestChar { public static void main(String args[])

{ System.out.println(" ASCII Character ");System.out.println(" for (int i = 32; i < 138 - 10; i+=10) ");System.out.println(" for (int j = i; j < i+10; j++) ");for (int i = 32; i < 138 - 10; i+=10){ for (int j = i; j < i+10; j++)

System.out.print(j + " " + (char)j + " ");System.out.println(); } } }

Page 41: Computer Programming 2.2

41

public class TestChar1 { public static void main(String args[])

{ char ch1, ch2;ch1 = 88;ch2 = 'Y';System.out.println("ch1 is " + ch1);System.out.println("ch2 is " + ch2); } }

Page 42: Computer Programming 2.2

42

Method toLowerCase ใชในกำรแปลงแบบอกษรจำกตวพมพใหญเปนตวพมพเลก

รปแบบ ชอตวแปร.toLowerCase() ตวอยำง String test = initials.toLowerCase()

Method toUpperCase ใชในเปนกำรแปลงแบบอกษรจำกตวพมพเลกเปนตวพมพใหญ

รปแบบ ชอตวแปร.toUpperCase() ตวอยำง String test = initials.toUpperCase()

กำรแปลงแบบอกษร

Page 43: Computer Programming 2.2

43

/* Method toLowerCase แปลงจำกอกษรตวพมพใหญเปนตวพมพเลก Method toUpperCase แปลงจำกอกษรตวพมพใหญเปนตวพมพเลก*/public class TesttoLowerCase{ public static void main(String[ ] args)

{ String firstName = "Aปปกร"; String lastName = "Mสงทอง"; String initials = firstName.substring(0,1) + lastName.substring(0,1); int age = 27; String password = initials.toLowerCase( ) + age; System.out.println(password); } }

Page 44: Computer Programming 2.2

44

กำรกำำหนดรปแบบของตวเลขMethod getNumberInstance ใชกำำหนดจำำนวนตวเลขหลงทศนยม โดยกำำหนดจำำนวนสงสดและตำำสด ซงตอง import package ของ Java ชอ ‘java.text’ เขำมำใชงำนดวย

ตวอยำง NumberFormat format1 =NumberFormat.getNumberInstance();

format1.setMaximumFractionDigits(7); format1.setMinimumFractionDigits(5);

Method getCurrencyInstance หำกตองกำรใหมเครองหมำย $ ปรำกฏรวมดวยโดยไมตองพมพเอง

ตวอยำง NumberFormat format2 = NumberFormat.getCurrencyInstance();

Page 45: Computer Programming 2.2

45

import java.text.*;public class TestgetNumberInstance{ public static void main (String [ ] args) // NumberFormat.getNumberInstance()

{ int quarters = 2;int dollars = 3;double total = dollars + quarters * 0.125;final double TAX_RATE = 8.5;double tax = total + TAX_RATE / 100;NumberFormat format1 = NumberFormat.getNumberInstance();format1.setMaximumFractionDigits(7);format1.setMinimumFractionDigits(5);System.out.println("Total : $" + format1.format(total));System.out.println("Tax : $" + format1.format(tax));

// NumberFormat.getCurrencyInstance()NumberFormat format2 = NumberFormat.getCurrencyInstance();System.out.println("Total : $" + format2.format(total));System.out.println("Tax : $" + format2.format(tax)); } }

Page 46: Computer Programming 2.2

46

import java.text.*;

DecimalFormat ชอออบเจกต = new DecimalFormat(pattern);

Page 47: Computer Programming 2.2

47

Page 48: Computer Programming 2.2

48

1. จงแสดงผลลพธจากการทำางานของโปรแกรมตอไปน (item1.java)

public class three{ public static void main(String args[])

{ int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6; int ans1 = c * c + c % b; int ans2 = b + e / c - c * d; int ans3 = b * (a - (d / e) / b) * (b - e % c); int ans4 = a + b - c / d / e * f; System.out.println("ans1 is " + ans1 + " และ " + "ans2 is " + ans2); System.out.println("ans3 is " + ans3 + " และ " + "ans4 is " + ans4);

}}

แบบฝกหด ครงท 1

Page 49: Computer Programming 2.2

49

2. จงแสดงผลลพธจากการทำางานของโปรแกรมตอไปน (item2.java)

public class four{ public static void main(String args[])

{ boolean a = true, b = true, c = true;boolean ans1 = !a && b;boolean ans2 = a && b || c;boolean ans3 = a || (b && c);boolean ans4 = a && b || c;System.out.print("ans1 is " + ans1 + " และ ");System.out.println("ans2 is " + ans2);System.out.print("ans3 is " + ans3 + " และ ");System.out.println("ans4 is " + ans4); } }

Page 50: Computer Programming 2.2

50

3. จงเขยนโปรแกรมเพอคำานวณผลลพธของนพจนตอไปน5 + 1 / 73 * 3 + 3 % 22 + 5 / 3 + -3 * 42 * (1 + -(4 / 5) / 2) * (2 - 5 % 3)

4. จงเขยนโปรแกรมเพอตรวจสอบผลการคำานวณของนพจนตอไปน

a+b*c!=b/c%2&&a*b/--c||b++/a>0a*b/c==b>0||a%b+--a/c++

Page 51: Computer Programming 2.2

51

การรบขอมลทางแปนพมพ ตองใชคำาสง IOException และ Package ชอ java.io รวมกนเสมอ

การใช System.in.read ใชรบขอมลเพยง 1 ตวอกษร โดยขอมลทเปน ASCII ตองแปลง

เปนตวอกษรกอนดวยวธ Type Casting คอ นำาชนดของขอมลผลลพธไปไวหนาของขอมลทตองการแปลง และ

ตวอยาง c = (char)System.in.read();

Page 52: Computer Programming 2.2

52

import java.io.*;class TestSysteminRead{ public static void main(String args [ ]) throws IOException

{ char c;System.out.print("Please key a character => ");c = (char)System.in.read();System.out.println("Your input is " + c); } }

Page 53: Computer Programming 2.2

53

import java.io.*;class TestSysteminRead1 { public static void main(String args [ ]) throws IOException

{ char buf = '\0'; System.out.println("Initial buf is " + buf); StringBuffer bufOut = new StringBuffer(); System.out.print("Please key one character => "); while ((buf = (char)System.in.read()) != '\n') { bufOut.append(buf); } System.out.println("Your input data is " + bufOut); } }

Page 54: Computer Programming 2.2

54

การใช BufferedReader รวมกบ InputStreamReader รปแบบInputStreamReader reader = new InputStreamReader (System.in);BufferedReader Stdin =new BufferedReader (reader);หรอBufferedReader Stdin = new BufferedReader (new InputStreamReader (System.in));และใช Method ชอ readLine ในการรบขอมลทางจอภาพดงน Input = Stdin.readLine(); ในการตรวจสอบความผดพลาดสามารถทำาไดโดยใชคำาสง try และ catch

Page 55: Computer Programming 2.2

55

import java.io.*;class TestBufferedReader{ public static void main(String[ ] args) throws IOException

{ BufferedReader Stdin = new BufferedReader (new InputStreamReader (System.in));

String Input = " "; System.out.print("Please key any data => "); Input = Stdin.readLine( ); System.out.println("Your input data is => " + Input); } }

Page 56: Computer Programming 2.2

56

import java.io.*;class TestTryCatch{ public static void main(String[ ] args)

{ try { BufferedReader Stdin =new BufferedReader

(new InputStreamReader (System.in)); String Input = " "; System.out.print("Please key any data => "); Input = Stdin.readLine( ); System.out.println("Your input data is => " + Input); }

catch (IOException e) { System.out.print(e); System.exit(1); } } }

Page 57: Computer Programming 2.2

57

// import java.io.BufferedReader;// import java.io.InputStreamReader;// import java.io.IOException;import java.io.*;class TestCalc{ public static void main(String args [ ]) throws IOException

{ final double A_Level = 4.0; final double B_Level = 3.0;

BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));

String input = " "; System.out.print("Amount of Subject grade A => "); input = stdin.readLine( );

int a = Integer.parseInt(input); System.out.print("Amount of Subject grade B => "); input = stdin.readLine( );

int b = Integer.parseInt(input); double GPA = ((a * A_Level) + (b * B_Level))/ (a + b);

System.out.println("GPA is " + GPA); } }

Page 58: Computer Programming 2.2

58

การรบขอมลจากแปนพมพโดยใช DataInputStream คลาส DataInputStream เปนสบคลาสของ FilterInputStream

และ InputStream ตวแปรทตองผานใหคลาส DataInputStream คอ System.in (InputStream)

รปแบบ DataInput input = new DataInputStream(System.in);คลาส DataInputStream ม Method ในการอานขอมล ดงน 1. readLine() อานขอมลตวอกษรทจบดวยการขนบรรทดใหม2. readInt() และ readLong() อานขอมลจำานวนเตม3. readFloat() และ readDouble() อานขอมลจำานวนจรง4. readUnsignedByte() อานจำานวนเตมทไมรวมเครองหมาย

Page 59: Computer Programming 2.2

59

import java.io.*;public class TestDataInput { public static void main(String args [ ]) throws IOException

{ DataInput input = new DataInputStream(System.in); String text = " "; int noOfguest = 0; double rate = 0;

System.out.print("Amount of guest => : "); try { noOfguest = Integer.parseInt(input.readLine());

// System.out.println("Amount of guest is " + noOfguest); System.out.print("Rate of rent per person per night is "); Double x = new Double(input.readLine()); rate = x.doubleValue(); }

catch (Exception e) { System.out.print(e);

System.exit(1); } System.out.println("Total rent is " + (rate * noOfguest)); } }