SlideShare a Scribd company logo
1 of 60
1
พื้นฐานในภาษา Java
2
ข ้อมูลพื้นฐาน (Primitive Data Type)
3
4
ตัวแปร (Variable)
การตั้งชื่อตัวแปร (Identifiers)
ควรมีความหมาย ไม่มีช่องว่างและเครื่องหมาย เช่น ? ! @ # % ^
& * ( ) [ ] { } . , ; : “ ‘ / และ 
ตัวแรกของชื่อตัวแปรควรเป็นตัวอักษรตัวพิมพ์เล็ก (a-z, _
หรือ $ )
ห ้ามใช ้คาศัพท์สงวน เช่น name, void, class, float ฯลฯ
ตัวพิมพ์ใหญ่/เล็ก มีความหมายต่างกัน
ไม่ควรใช ้ตัวพิมพ์ใหญ่ทุกตัว เพราะอาจเชื่อมโยงกับภาษาอื่นไม่ไ้ ้
5
การประกาศตัวแปร
[<access_specifier>] [<modifier>] <data_type> <variable_name1>
[, <variable_name2>] ...;
public ใช้นิยามตัวแปรเพื่อให้นาไปใช้กับ Class หรือโปรแกรม
อื่นได้
private ใช้นิยามตัวแปรเพื่อให้ใช้ได้เฉพาะใน Class ที่สร้างตัว
แปรหรือ Method นั้นขึ้นมา
protected ใช้นิยามตัวแปรเพื่อให้ใช้ได้เฉพาะ Class ที่สร้าง
ขึ้นมาด้วยวิธีการสืบทอด (Inheritance) โดยปกติใช้กับ Base
Class
static ใช้นิยามตัวแปรที่ต้องการให้ใช้งานได้กับทุก Method ใน
Class
final ใช้นิยามตัวแปรที่ต้องการใช้เก็บข้อมูลค่าคงที่ (Constant)
ซึ่งไม่สามารถเปลี่ยนค่าได้
6
การกาหนดค่าให้กับตัวแปร
[<access_specifier>] [<modifier>] <data_type>
<variable_name1> = <value> [, <variable_name2> = <value>]...;
หรือ
[<access_specifier>] [<modifier>] <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;
7
การกาหนดค่าจานวนจริง
float d1 = 34.0 - 0.1;
double d2 = 1.0/2.0;
static final float PI = 3.141159;
private float salary = 0.0F;
static final float TAX_RATE = .0725F;
การกาหนดค่าตรรกะ
boolean done =true;
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); } }
9
การกาหนดค่าตัวอักษร
ต ้องอยู่ในสัญลักษณ์หยา้ฝน (Single Quote)
10
11
String
String message = “Welcome”;
String firstName = “Sippakorn”, lastName = “Saengthong”;
private String name;
private String name = “ ”;
String name1, name2;
name1 = “Tanisorn”; name2 = name1;
การหาความยาวของ String
int n = fname.length();
การดึงข้อความบางส่วนที่เก็บในตัวแปรแบบ String
String fname = “Samphan”;
String sub = fname.substring (0,4);
String sub = fname.substring (1);
การเชื่อมต่อข้อความ
String s1 = “Chantana”
String s2 = “Promsiri”
String name1 = s1 + s2;
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); } }
13
14
15
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;
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); } }
18
// Floating Arithmetic Operators
public 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); } }
19
// Arithmetic Assignment Operators : Integer
public 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); } }
20
// Arithmetic Assignment Operators : Float
public 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); } }
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); } }
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); } }
23
Bitwise Operators
Boolean 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)
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));} }
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
26
//Relational Operator
public 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)); } }
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 Operators
System.out.println("1. Boolean Logical Operators");
// Logical And
System.out.println("Logical And => a & b = " + (a & b));
// Logical Or
System.out.println("Logical Or => a | b = " + (a | b));
// Logical Exclusive Or
System.out.println("Logical Exclusive Or => a ^ b = " + (a ^ b));
// Logical Unary Not
System.out.println("Logical Unary Not => !a = " + (!a));
System.out.println();
} }
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 Operators
System.out.println("2. Short-Circuit Logical Operators");
// Short-Circuit And
System.out.println("Short-Circuit And => a && b = " + (a && b));
// Short-Circuit Or
System.out.println("Short-Circuit Or => a || b = " + (a || b));
System.out.println();
// กลุ่มที่ 3 Assignment Logical Operators
System.out.println("3. Assignment Logical Operators");
// And Assignment
System.out.println("And Assignment => a &= b = " + (a &= b));
// Or Assignment
System.out.println("Or Assignment => a |= b = " + (a |= b));
// Exclusive Or Assignment
System.out.println("Exclusive Or Assignment => a ^= b = " + (a ^= b)); } }
29
Conditional Operators
(<condition>) ? <expression 1> : <expression 2>
//Conditional Operator
public class TestCondOper
{ public static void main(String args[])
{ int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
//input x = 5, y = 3
System.out.println((x > y)? x : y); } }
30
ลา้ับในการประมวลผลของ Operator
ลาดับ Operator ประเภท Assoc.
1 ()
2 ++ (Increment), -- (Decrement)
!
~ (Complement)
(type_cast)
การคานวณ
boolean
integer
ทุกรูปแบบ
R
R
R
R
3 *, /, % การคานวณ L
4 +, - การคานวณ L
5 << (Left shift), >> (Right shift),
>>> (Zero fill)
จานวนเต็ม L
6 <, <=, >, >=, Instanceof() การเปรียบเทียบ
object
L
7 ==, != ข ้อมูลพื้นฐาน
และ object
L
31
ลาดับ Operator ประเภท Assoc.
8 & (Bitwise AND) จานวนเต็ม L
9 ^ (Bitwise XOR) จานวนเต็ม L
10 | (Bitwise OR) จานวนเต็ม L
11 && (AND) boolean L
12 || (OR) boolean L
13 ?: boolean R
14 =, *=, /=, %=, +=, -=, <<=, >>=,
>>>=, &=,
^=, !=
อื่น ๆ R
32
ให ้ประมวลผลหาค่าของนิพจน์
a * b – c != a / b – c && --a > b++ || b % --c > 0
1. Increment และ Decrement Operator
2. ตัวกระทาทางคณิตศาสตร์ *, /, %
3. ตัวกระทาทางคณิตศาสตร์ -
4. Relational Operator
5. ไม่เท่ากัน
6. &&
7. ||
1 1 1
2 2 2
3 3
4 4
5
6
7
33
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
34
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); } }
35
3. จากข ้อมูลคือ data=Faculty of Liberal Arts and Science
จงเขียนโปรแกรม item3.java เพื่อให ้มีการแส้งผลลัพธ์ว่า
FLAS พร ้อมทั้งให ้แส้งผลตัวอักษร 3 ตัวแรกของชื่อนิสิต
และตัวอักษร 3 ตัวสุ้ท ้ายของนามสกุลนิสิต
ส่งภายในวัน
36
การแปลงชนิ้ของตัวแปร (Type Conversion)
1.การแปลงชนิ้ข ้อมูลโ้ยอัตโนมัติ (Implicit)
กรณีที่นิพจน์ประกอบ้ ้วยตัวแปรหลายชนิ้ Java จะตรวจสอบ
ชนิ้ ข ้อมูลของตัวแปรในนิพจน์ แล ้วเปลี่ยนชนิ้ข ้อมูลให ้เป็น
แบบที่ใช ้เนื้อที่ในหน่วยความจามากที่สุ้ โ้ยจะแปลงชนิ้
ข ้อมูลโ้ยอัตโนมัติ เมื่อชนิ้ข ้อมูลของตัวแปรสามารถใช ้
ร่วมกันไ้ ้และตัวแปรปลายทางมีขนา้ใหญ่กว่าหรือเท่ากับตัว
แปรต ้นทาง
2.การแปลงชนิ้ข ้อมูลแบบ Explicit หรือ Type Casting
เป็นการประกาศเปลี่ยนแปลงประเภทของข ้อมูลโ้ยผู้ใช ้เอง
(target_type) expression;
37
3. การแปลงชนิ้ข ้อมูลโ้ยใช ้Type Wrapper
เป็นการสร ้าง Object ขึ้นมาก่อนที่จะเรียก Method มาใช ้งาน
public double doubleValue()
public float floatValue()
public int intValue()
public long longValue()
public String toString()
38
// Type Conversion : Implicit
public 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);
39
/* 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))); }}
40
// Type Conversion : Explicit หรือ Type Casting
public 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)); } }
41
/* 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();
42
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); } }
43
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(); } } }
44
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); } }
45
Method toLowerCase ใช ้ในการแปลงแบบอักษรจากตัวพิมพ์
ใหญ่เป็นตัวพิมพ์เล็ก
รูปแบบ ชื่อตัวแปร.toLowerCase()
ตัวอย่าง String test = initials.toLowerCase()
Method toUpperCase ใช ้ในเป็นการแปลงแบบอักษรจาก
ตัวพิมพ์เล็กเป็นตัวพิมพ์ใหญ่
รูปแบบ ชื่อตัวแปร.toUpperCase()
ตัวอย่าง String test = initials.toUpperCase()
การแปลงแบบอักษร
46
/* 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); } }
47
การกาหน้รูปแบบของตัวเลข
Method getNumberInstance ใช ้กาหน้จานวนตัวเลขหลังทศนิยม
โ้ยกาหน้จานวนสูงสุ้และต่าสุ้ ซึ่งต ้อง import package ของ Java
ชื่อ ‘java.text’ เข ้ามาใช ้งาน้ ้วย
ตัวอย่าง
NumberFormat format1 =NumberFormat.getNumberInstance();
format1.setMaximumFractionDigits(7);
format1.setMinimumFractionDigits(5);
Method getCurrencyInstance หากต ้องการให ้มีเครื่องหมาย $ ปรากฏ
ร่วม้ ้วยโ้ยไม่ต ้องพิมพ์เอง
ตัวอย่าง
NumberFormat format2 = NumberFormat.getCurrencyInstance();
48
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)); } }
49
import java.text.*;
DecimalFormat ชื่อออบเจ็กต์ = new DecimalFormat(pattern);
50
51
การรับข ้อมูลทางแป้นพิมพ์
ต ้องใช ้คาสั่ง IOException และ Package ชื่อ java.io ร่วมกันเสมอ
การใช ้System.in.read
ใช ้รับข ้อมูลเพียง 1 ตัวอักษร โ้ยข ้อมูลที่เป็น ASCII ต ้องแปลง
เป็นตัวอักษรก่อน้ ้วยวิธี Type Casting คือ นาชนิ้ของข ้อมูล
ผลลัพธ์ไปไว ้หน้าของข ้อมูลที่ต ้องการแปลง และ
ตัวอย่าง c = (char)System.in.read();
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); } }
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); } }
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
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); } }
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); } } }
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); } }
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() อ่านจานวนเต็มที่ไม่รวมเครื่องหมาย
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)); } }
60
แบบฝึกหั้ที่ 1
จงเขียนโปรแกรมเพื่อคานวณผลลัพธ์ของนิพจน์ต่อไปนี้
5 + 1 / 7
3 * 3 + 3 % 2
2 + 5 / 3 + -3 * 4
2 * (1 + -(4 / 5) / 2) * (2 - 5 % 3)
จงเขียนโปรแกรมเพื่อตรวจสอบผลการคานวณของนิพจน์
ต่อไปนี้
a+b*c!=b/c%2&&a*b/--c||b++/a>0
a*b/c==b>0||a%b+--a/c++

More Related Content

What's hot

Java-Answer Chapter 07 (For Print)
Java-Answer Chapter 07 (For Print)Java-Answer Chapter 07 (For Print)
Java-Answer Chapter 07 (For Print)Wongyos Keardsri
 
Java-Answer Chapter 01-04 (For Print)
Java-Answer Chapter 01-04 (For Print)Java-Answer Chapter 01-04 (For Print)
Java-Answer Chapter 01-04 (For Print)Wongyos Keardsri
 
Java-Answer Chapter 12-13 (For Print)
Java-Answer Chapter 12-13 (For Print)Java-Answer Chapter 12-13 (For Print)
Java-Answer Chapter 12-13 (For Print)Wongyos Keardsri
 

What's hot (6)

Java-Answer Chapter 10-11
Java-Answer Chapter 10-11Java-Answer Chapter 10-11
Java-Answer Chapter 10-11
 
Java-Answer Chapter 07 (For Print)
Java-Answer Chapter 07 (For Print)Java-Answer Chapter 07 (For Print)
Java-Answer Chapter 07 (For Print)
 
Java-Answer Chapter 01-04 (For Print)
Java-Answer Chapter 01-04 (For Print)Java-Answer Chapter 01-04 (For Print)
Java-Answer Chapter 01-04 (For Print)
 
Java-Answer Chapter 12-13 (For Print)
Java-Answer Chapter 12-13 (For Print)Java-Answer Chapter 12-13 (For Print)
Java-Answer Chapter 12-13 (For Print)
 
Java-Answer Chapter 12-13
Java-Answer Chapter 12-13Java-Answer Chapter 12-13
Java-Answer Chapter 12-13
 
Java-Answer Chapter 01-04
Java-Answer Chapter 01-04Java-Answer Chapter 01-04
Java-Answer Chapter 01-04
 

Similar to Computer Programming 2.1

Java Programming: อะเรย์และคอลเล็กชั่น
Java Programming: อะเรย์และคอลเล็กชั่นJava Programming: อะเรย์และคอลเล็กชั่น
Java Programming: อะเรย์และคอลเล็กชั่นThanachart Numnonda
 
Java Programming [6/12] : Object Oriented Java Programming
Java Programming [6/12] : Object Oriented Java ProgrammingJava Programming [6/12] : Object Oriented Java Programming
Java Programming [6/12] : Object Oriented Java ProgrammingIMC Institute
 
Java Programming: โครงสร้างควบคุม
Java Programming: โครงสร้างควบคุมJava Programming: โครงสร้างควบคุม
Java Programming: โครงสร้างควบคุมThanachart Numnonda
 
Java Programming [9/12]: Exception Handling
Java Programming [9/12]: Exception HandlingJava Programming [9/12]: Exception Handling
Java Programming [9/12]: Exception HandlingIMC Institute
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นFinian Nian
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นFinian Nian
 
Java Programming: การเขียนโปรแกรมภาษาจาวาเชิงอ็อบเจกต์
Java Programming: การเขียนโปรแกรมภาษาจาวาเชิงอ็อบเจกต์Java Programming: การเขียนโปรแกรมภาษาจาวาเชิงอ็อบเจกต์
Java Programming: การเขียนโปรแกรมภาษาจาวาเชิงอ็อบเจกต์Thanachart Numnonda
 
กลุ่มที่ 6 โปรแกรมย่อยและฟังก์ชันมาตรฐาน
กลุ่มที่ 6 โปรแกรมย่อยและฟังก์ชันมาตรฐาน กลุ่มที่ 6 โปรแกรมย่อยและฟังก์ชันมาตรฐาน
กลุ่มที่ 6 โปรแกรมย่อยและฟังก์ชันมาตรฐาน Kanchana Theugcharoon
 

Similar to Computer Programming 2.1 (20)

Java Programming: อะเรย์และคอลเล็กชั่น
Java Programming: อะเรย์และคอลเล็กชั่นJava Programming: อะเรย์และคอลเล็กชั่น
Java Programming: อะเรย์และคอลเล็กชั่น
 
Java Programming [6/12] : Object Oriented Java Programming
Java Programming [6/12] : Object Oriented Java ProgrammingJava Programming [6/12] : Object Oriented Java Programming
Java Programming [6/12] : Object Oriented Java Programming
 
Java Programming: โครงสร้างควบคุม
Java Programming: โครงสร้างควบคุมJava Programming: โครงสร้างควบคุม
Java Programming: โครงสร้างควบคุม
 
Java Programming [9/12]: Exception Handling
Java Programming [9/12]: Exception HandlingJava Programming [9/12]: Exception Handling
Java Programming [9/12]: Exception Handling
 
Python101
Python101Python101
Python101
 
C lang
C langC lang
C lang
 
Method part2
Method part2Method part2
Method part2
 
3.Expression
3.Expression3.Expression
3.Expression
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
 
power point.
power point.power point.
power point.
 
เมธอด
เมธอดเมธอด
เมธอด
 
Java Programming: การเขียนโปรแกรมภาษาจาวาเชิงอ็อบเจกต์
Java Programming: การเขียนโปรแกรมภาษาจาวาเชิงอ็อบเจกต์Java Programming: การเขียนโปรแกรมภาษาจาวาเชิงอ็อบเจกต์
Java Programming: การเขียนโปรแกรมภาษาจาวาเชิงอ็อบเจกต์
 
1 test
1  test1  test
1 test
 
กลุ่มที่ 6 โปรแกรมย่อยและฟังก์ชันมาตรฐาน
กลุ่มที่ 6 โปรแกรมย่อยและฟังก์ชันมาตรฐาน กลุ่มที่ 6 โปรแกรมย่อยและฟังก์ชันมาตรฐาน
กลุ่มที่ 6 โปรแกรมย่อยและฟังก์ชันมาตรฐาน
 
08 arrays
08 arrays08 arrays
08 arrays
 
Java-Chapter 08 Methods
Java-Chapter 08 MethodsJava-Chapter 08 Methods
Java-Chapter 08 Methods
 
Methods
MethodsMethods
Methods
 
Methods
MethodsMethods
Methods
 
7 2โครงสร้าง
7 2โครงสร้าง7 2โครงสร้าง
7 2โครงสร้าง
 

More from Saranyu Srisrontong

More from Saranyu Srisrontong (11)

Computer Programming 1
Computer Programming 1Computer Programming 1
Computer Programming 1
 
Lab Computer Programming 1
Lab Computer Programming 1Lab Computer Programming 1
Lab Computer Programming 1
 
Computer Programming 4
Computer Programming 4Computer Programming 4
Computer Programming 4
 
Ac current46
Ac current46Ac current46
Ac current46
 
electric potential
electric potentialelectric potential
electric potential
 
พลังงานไฟฟ้า
พลังงานไฟฟ้าพลังงานไฟฟ้า
พลังงานไฟฟ้า
 
Physics2 1
Physics2 1Physics2 1
Physics2 1
 
Intellec.pro for final exam
Intellec.pro for final examIntellec.pro for final exam
Intellec.pro for final exam
 
การแก้ปัญหาการออกแบบและพัฒนาขั้นตอนวิธี
การแก้ปัญหาการออกแบบและพัฒนาขั้นตอนวิธีการแก้ปัญหาการออกแบบและพัฒนาขั้นตอนวิธี
การแก้ปัญหาการออกแบบและพัฒนาขั้นตอนวิธี
 
Network fundamental
Network fundamentalNetwork fundamental
Network fundamental
 
Computer systemarchitecture
Computer systemarchitectureComputer systemarchitecture
Computer systemarchitecture
 

Computer Programming 2.1

  • 3. 3
  • 4. 4 ตัวแปร (Variable) การตั้งชื่อตัวแปร (Identifiers) ควรมีความหมาย ไม่มีช่องว่างและเครื่องหมาย เช่น ? ! @ # % ^ & * ( ) [ ] { } . , ; : “ ‘ / และ ตัวแรกของชื่อตัวแปรควรเป็นตัวอักษรตัวพิมพ์เล็ก (a-z, _ หรือ $ ) ห ้ามใช ้คาศัพท์สงวน เช่น name, void, class, float ฯลฯ ตัวพิมพ์ใหญ่/เล็ก มีความหมายต่างกัน ไม่ควรใช ้ตัวพิมพ์ใหญ่ทุกตัว เพราะอาจเชื่อมโยงกับภาษาอื่นไม่ไ้ ้
  • 5. 5 การประกาศตัวแปร [<access_specifier>] [<modifier>] <data_type> <variable_name1> [, <variable_name2>] ...; public ใช้นิยามตัวแปรเพื่อให้นาไปใช้กับ Class หรือโปรแกรม อื่นได้ private ใช้นิยามตัวแปรเพื่อให้ใช้ได้เฉพาะใน Class ที่สร้างตัว แปรหรือ Method นั้นขึ้นมา protected ใช้นิยามตัวแปรเพื่อให้ใช้ได้เฉพาะ Class ที่สร้าง ขึ้นมาด้วยวิธีการสืบทอด (Inheritance) โดยปกติใช้กับ Base Class static ใช้นิยามตัวแปรที่ต้องการให้ใช้งานได้กับทุก Method ใน Class final ใช้นิยามตัวแปรที่ต้องการใช้เก็บข้อมูลค่าคงที่ (Constant) ซึ่งไม่สามารถเปลี่ยนค่าได้
  • 6. 6 การกาหนดค่าให้กับตัวแปร [<access_specifier>] [<modifier>] <data_type> <variable_name1> = <value> [, <variable_name2> = <value>]...; หรือ [<access_specifier>] [<modifier>] <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;
  • 7. 7 การกาหนดค่าจานวนจริง float d1 = 34.0 - 0.1; double d2 = 1.0/2.0; static final float PI = 3.141159; private float salary = 0.0F; static final float TAX_RATE = .0725F; การกาหนดค่าตรรกะ boolean done =true;
  • 8. 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); } }
  • 10. 10
  • 11. 11 String String message = “Welcome”; String firstName = “Sippakorn”, lastName = “Saengthong”; private String name; private String name = “ ”; String name1, name2; name1 = “Tanisorn”; name2 = name1; การหาความยาวของ String int n = fname.length(); การดึงข้อความบางส่วนที่เก็บในตัวแปรแบบ String String fname = “Samphan”; String sub = fname.substring (0,4); String sub = fname.substring (1); การเชื่อมต่อข้อความ String s1 = “Chantana” String s2 = “Promsiri” String name1 = s1 + s2;
  • 12. 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); } }
  • 13. 13
  • 14. 14
  • 15. 15
  • 16. 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;
  • 17. 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); } }
  • 18. 18 // Floating Arithmetic Operators public 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); } }
  • 19. 19 // Arithmetic Assignment Operators : Integer public 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); } }
  • 20. 20 // Arithmetic Assignment Operators : Float public 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); } }
  • 21. 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); } }
  • 22. 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); } }
  • 23. 23 Bitwise Operators Boolean 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)
  • 24. 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));} }
  • 25. 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
  • 26. 26 //Relational Operator public 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)); } }
  • 27. 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 Operators System.out.println("1. Boolean Logical Operators"); // Logical And System.out.println("Logical And => a & b = " + (a & b)); // Logical Or System.out.println("Logical Or => a | b = " + (a | b)); // Logical Exclusive Or System.out.println("Logical Exclusive Or => a ^ b = " + (a ^ b)); // Logical Unary Not System.out.println("Logical Unary Not => !a = " + (!a)); System.out.println(); } }
  • 28. 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 Operators System.out.println("2. Short-Circuit Logical Operators"); // Short-Circuit And System.out.println("Short-Circuit And => a && b = " + (a && b)); // Short-Circuit Or System.out.println("Short-Circuit Or => a || b = " + (a || b)); System.out.println(); // กลุ่มที่ 3 Assignment Logical Operators System.out.println("3. Assignment Logical Operators"); // And Assignment System.out.println("And Assignment => a &= b = " + (a &= b)); // Or Assignment System.out.println("Or Assignment => a |= b = " + (a |= b)); // Exclusive Or Assignment System.out.println("Exclusive Or Assignment => a ^= b = " + (a ^= b)); } }
  • 29. 29 Conditional Operators (<condition>) ? <expression 1> : <expression 2> //Conditional Operator public class TestCondOper { public static void main(String args[]) { int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); //input x = 5, y = 3 System.out.println((x > y)? x : y); } }
  • 30. 30 ลา้ับในการประมวลผลของ Operator ลาดับ Operator ประเภท Assoc. 1 () 2 ++ (Increment), -- (Decrement) ! ~ (Complement) (type_cast) การคานวณ boolean integer ทุกรูปแบบ R R R R 3 *, /, % การคานวณ L 4 +, - การคานวณ L 5 << (Left shift), >> (Right shift), >>> (Zero fill) จานวนเต็ม L 6 <, <=, >, >=, Instanceof() การเปรียบเทียบ object L 7 ==, != ข ้อมูลพื้นฐาน และ object L
  • 31. 31 ลาดับ Operator ประเภท Assoc. 8 & (Bitwise AND) จานวนเต็ม L 9 ^ (Bitwise XOR) จานวนเต็ม L 10 | (Bitwise OR) จานวนเต็ม L 11 && (AND) boolean L 12 || (OR) boolean L 13 ?: boolean R 14 =, *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, != อื่น ๆ R
  • 32. 32 ให ้ประมวลผลหาค่าของนิพจน์ a * b – c != a / b – c && --a > b++ || b % --c > 0 1. Increment และ Decrement Operator 2. ตัวกระทาทางคณิตศาสตร์ *, /, % 3. ตัวกระทาทางคณิตศาสตร์ - 4. Relational Operator 5. ไม่เท่ากัน 6. && 7. || 1 1 1 2 2 2 3 3 4 4 5 6 7
  • 33. 33 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
  • 34. 34 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); } }
  • 35. 35 3. จากข ้อมูลคือ data=Faculty of Liberal Arts and Science จงเขียนโปรแกรม item3.java เพื่อให ้มีการแส้งผลลัพธ์ว่า FLAS พร ้อมทั้งให ้แส้งผลตัวอักษร 3 ตัวแรกของชื่อนิสิต และตัวอักษร 3 ตัวสุ้ท ้ายของนามสกุลนิสิต ส่งภายในวัน
  • 36. 36 การแปลงชนิ้ของตัวแปร (Type Conversion) 1.การแปลงชนิ้ข ้อมูลโ้ยอัตโนมัติ (Implicit) กรณีที่นิพจน์ประกอบ้ ้วยตัวแปรหลายชนิ้ Java จะตรวจสอบ ชนิ้ ข ้อมูลของตัวแปรในนิพจน์ แล ้วเปลี่ยนชนิ้ข ้อมูลให ้เป็น แบบที่ใช ้เนื้อที่ในหน่วยความจามากที่สุ้ โ้ยจะแปลงชนิ้ ข ้อมูลโ้ยอัตโนมัติ เมื่อชนิ้ข ้อมูลของตัวแปรสามารถใช ้ ร่วมกันไ้ ้และตัวแปรปลายทางมีขนา้ใหญ่กว่าหรือเท่ากับตัว แปรต ้นทาง 2.การแปลงชนิ้ข ้อมูลแบบ Explicit หรือ Type Casting เป็นการประกาศเปลี่ยนแปลงประเภทของข ้อมูลโ้ยผู้ใช ้เอง (target_type) expression;
  • 37. 37 3. การแปลงชนิ้ข ้อมูลโ้ยใช ้Type Wrapper เป็นการสร ้าง Object ขึ้นมาก่อนที่จะเรียก Method มาใช ้งาน public double doubleValue() public float floatValue() public int intValue() public long longValue() public String toString()
  • 38. 38 // Type Conversion : Implicit public 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);
  • 39. 39 /* 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))); }}
  • 40. 40 // Type Conversion : Explicit หรือ Type Casting public 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)); } }
  • 41. 41 /* 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();
  • 42. 42 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); } }
  • 43. 43 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(); } } }
  • 44. 44 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); } }
  • 45. 45 Method toLowerCase ใช ้ในการแปลงแบบอักษรจากตัวพิมพ์ ใหญ่เป็นตัวพิมพ์เล็ก รูปแบบ ชื่อตัวแปร.toLowerCase() ตัวอย่าง String test = initials.toLowerCase() Method toUpperCase ใช ้ในเป็นการแปลงแบบอักษรจาก ตัวพิมพ์เล็กเป็นตัวพิมพ์ใหญ่ รูปแบบ ชื่อตัวแปร.toUpperCase() ตัวอย่าง String test = initials.toUpperCase() การแปลงแบบอักษร
  • 46. 46 /* 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); } }
  • 47. 47 การกาหน้รูปแบบของตัวเลข Method getNumberInstance ใช ้กาหน้จานวนตัวเลขหลังทศนิยม โ้ยกาหน้จานวนสูงสุ้และต่าสุ้ ซึ่งต ้อง import package ของ Java ชื่อ ‘java.text’ เข ้ามาใช ้งาน้ ้วย ตัวอย่าง NumberFormat format1 =NumberFormat.getNumberInstance(); format1.setMaximumFractionDigits(7); format1.setMinimumFractionDigits(5); Method getCurrencyInstance หากต ้องการให ้มีเครื่องหมาย $ ปรากฏ ร่วม้ ้วยโ้ยไม่ต ้องพิมพ์เอง ตัวอย่าง NumberFormat format2 = NumberFormat.getCurrencyInstance();
  • 48. 48 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)); } }
  • 50. 50
  • 51. 51 การรับข ้อมูลทางแป้นพิมพ์ ต ้องใช ้คาสั่ง IOException และ Package ชื่อ java.io ร่วมกันเสมอ การใช ้System.in.read ใช ้รับข ้อมูลเพียง 1 ตัวอักษร โ้ยข ้อมูลที่เป็น ASCII ต ้องแปลง เป็นตัวอักษรก่อน้ ้วยวิธี Type Casting คือ นาชนิ้ของข ้อมูล ผลลัพธ์ไปไว ้หน้าของข ้อมูลที่ต ้องการแปลง และ ตัวอย่าง c = (char)System.in.read();
  • 52. 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); } }
  • 53. 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); } }
  • 54. 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
  • 55. 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); } }
  • 56. 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); } } }
  • 57. 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); } }
  • 58. 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() อ่านจานวนเต็มที่ไม่รวมเครื่องหมาย
  • 59. 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)); } }
  • 60. 60 แบบฝึกหั้ที่ 1 จงเขียนโปรแกรมเพื่อคานวณผลลัพธ์ของนิพจน์ต่อไปนี้ 5 + 1 / 7 3 * 3 + 3 % 2 2 + 5 / 3 + -3 * 4 2 * (1 + -(4 / 5) / 2) * (2 - 5 % 3) จงเขียนโปรแกรมเพื่อตรวจสอบผลการคานวณของนิพจน์ ต่อไปนี้ a+b*c!=b/c%2&&a*b/--c||b++/a>0 a*b/c==b>0||a%b+--a/c++