แสดงบทความที่มีป้ายกำกับ Java แสดงบทความทั้งหมด

Compiling and Running with Arguments in Java

Compiling and Running with Arguments


               ในส่วนนี้เป็นการพูดถึงเมื่อเราต้องการพิมพ์บางอย่างออกทางหน้าจอ เราต้องคอมไพล์โค้ดของคุณและรันมัน ซึ่งเราต้องใช้คำสั่งเพื่อให้มันทำงานนั่นคือ
  • java (or java.exe)
  • javac (or javac.exe)
นั่นทำให้คุณต้องไปหาโหลดและติดตั้งตัว JDK (Java Development Kit)

ถ้าเรานำ code จากบทความก่อนหน้านี้มาใส่มันลงไปให้ไฟล์ MyFirstClass.java เราจะต้องคอมไพล์และรัน :


javac MyFirstClass.java

มันจะสร้างไฟล์ MyFirstClass.class แล้วนำมาคอมไพล์เป็น Java code เพื่อรันมัน เราต้องการรัน Java เราใช้แค่ชื่อของ Class เช่น

แบบนี้ผิด
java MyFirstClass.class

แบบนี้ถูกต้อง
java MyFirstClass



Arguments


             ภาษา Java ใน method หลักเราเรียกใช้ Array of String เป็น argument ซึ่งเป็นช่องทางในนำค่าต่างๆ จาก Command Line มาสู่โปรแกรมของเรา และทุก Arrays ในภาษา java จะมีตัวแปร lenght เป็นตัวนับความยาวของ Array เราสามารถเข้าถึง Array แบบง่ายๆ โดย for

public class Arguments {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}

จากนั้นลองคอมไพล์แล้วรัน
javac Arguments.java
java Arguments arg0 arg1 arg2

การเขียนโปรแกรม java Objects

Objects


ทุกสิ่งในภาษา Java จะอยู่ใน Classes และ Objects

class Point {
    int x;
    int y;
}

ใน class point มีการประกาศตัวแปร x , y เราสร้าง object ชื่อ p โดยต้องใช้คำสั่ง new


Point p = new Point();

ในกรณีนี้เราประกาศโดยใช้ default constructor คือไม่มีการให้ค่าเริ่มต้น หรือเราสามารถ constructor เองได้ โดย

class Point {
    int x;
    int y;
    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

ตอนนี้เราสามารถกำหนดค่าเริ่มต้นให้กับ Object ได้แล้วเช่น new Point(4, 1).


เราสามารถสร้างได้มากกว่า 1 constuctor ดังนั้น Point  สามารถสร้างได้หลายแบบ ลองสร้างอีกครั้ง

class Point {
    int x;
    int y;
    Point() {
        this(0, 0);
    }
    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

ข้อสังเกตในการใช้  this นี้ เราสามารถใช้มันใน constuctor ในการเรียก constuctor อื่น ใน class ของเราเอง

หลังจากเราประกาศ p แล้วสามารถเข้าถึงตัวแปรภายใน Object ได้เลย


p.x = 3;
p.y = 6;

Methods

เราสามารถประกาศ method ของ point ได้แล้ว

class Point {
    ... // code ของเราก่อนหน้านี้
    void printPoint() {
        System.out.println("(" + x + "," + y + ")");
    }
    Point center(Point other) {
        // เราคืนค่าจุดศูนย์กลางของจุดนี้และจุดอื่น
        return new Point((x + other.x) / 2, (y + other.y) / 2);
    }


Public and Private

เมื่อเราใช้  private  ก่อนตัวแปรหรือ method ในคลาสนั้น นั่นหมายถึงคลาสอื่นจะไม่สามารถใช้ตัวแปรนี้ได้ และเมื่อเราใช้  public หมายถึงคลาสไหนก็มาใช้ได้ ปกติเราจะเห็น Constuctor ใช้  public 

แบบฝึกหัด

สร้าง method ใหม่ชื่อ scale, จะสร้างจุดที่ใกล้จุด (0,0) ที่สุด โดยลดค่าที่ละครึ่งเช่น (8 , 4) หลังจากนั้นจะเป็น (4 , 2) , (1, 1)

class Point 
    private double x;
    private double y;
    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
    public void print() {
        System.out.println("(" + x + "," + y + ")");
    }
    // สร้างตรงนี้
}

public class Main {
    public static void main(String[] args) {
        Point p = new Point(32, 32);
        for (int i = 0; i < 5; i++) {
            p.scale();
            p.print();
        }
    }
}

class Point {
    private double x;
    private double y;
    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
    public void print() {
        System.out.println("(" + x + "," + y + ")");
    }
    public void scale(){
    x = x/2;
    y = y/2;
    }
}

public class Main {
    public static void main(String[] args) {
        Point p = new Point(32, 32);
        for (int i = 0; i < 5; i++) {
            p.scale();
            p.print();
        }
    }
} 

การเขียนโปรแกรม Java Functions (Methods)

Java Functions (Methods)



ในภาษา Java ต้องสร้าง Functions ไว้ใน class และภาษา java เราเรียกว่า Methods มาดูตัวอย่างกัน

public class Main {
    public static void test() {
        // โค้ดโปรแกรม
    }
}

test คือชื่อของ method นี้ ซึ่งอยู่ในคลาส Main

Arguments

method ของภาษา Java จะส่งค่าเป็น passed by value หมายถึง การ copies ค่าเมื่อ method ทำงาน ตัวอย่าง

public void bar(int num1, int num2) {
    ...
}

ยกตัวอย่างเมื่อมีการเรียกใช้ method bar

int a = 3;
int b = 5;
bar(a, b);

เมื่อ method ทำงาน bar(a, b) จะส่งค่า a=3, b=5 ไปใน method ซึ่งจะเปรียบเสมือน

int num1 = a;
int num2 = b;
หรือ 

public void bar(int num1 = a, int num2 = b) {
    ...
}

หมายถึง ค่า a จะคัดลอกไปสู่ num1 และค่า b คัดลอกไปสู่ num2 เรียงตามลำดับโดยไม่กระทบค่า a , b
จากนั้นก็จะทำส่วนที่เหลือของ method

แล้วถ้า arguments เป็น object บ้าง การทำงานก็คล้ายๆ กัน ต่างกันนิดเดียวเท่านั้น ตัวอย่าง

public void bar2(Student s1, Student s2) {
    ...
}

มี method อยู่ 2 ตัวคือ joe , jack และเรียกใช้ method bar2 พร้อมส่งค่าไป

Student joe = new Student("joe");
Student jack = new Student("jack");
bar2(joe, jack);

แล้วการส่งค่าก็จะเปรียบเสมือนการ copy ค่า (pass by value)
Student s1 = joe;
Student s2 = jack;

แต่ถ้าเป็น object จะต่างกันนิดหนึ่งตรงที่ object  s1  กับ  joe  มีตำแหน่งอ้างอิงเดียวกันทำให้ s1 == joe เป็น true หมายความว่าเมื่อเปลียนค่า s1  joe ก็จะถูกกระทบคือเปลี่ยนตาม แต่ถ้าสร้าง s1 ในตำแหน่งอื่น ก็จะไม่กระทบกับ joe


s1.setName("Chuck"); // เปลี่ยน s1 ให้เป็น Chuck ทำให้ตอนนี้ joe เปลี่ยนเป็น Chuck ตามไปด้วย
s1 = new Student("Norris"); // s1 ถูกสร้างขึ้นใหม่ชื่อ Norris อ้างอิงตำแหน่งใหม่ทำให้ต่างจาก joe
// s1 == joe   ทำให้ไม่ true อีกต่อไป

Non static methods

non static methods ในภาษา Java ถูกใช้มากกว่า static method ซึ่ง non static methods จะทำงานภายใต้ object เท่านั้น ไม่ทำงานใน class
non static methods สามารถเรียกใช้และเปลี่ยนค่าใน object

public class Student {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

การเรียกใช้ method จะเรียกผ่าน object ชนิด student

Student s = new Student();
s.setName("Danielle");
String name = s.getName();

Student.setName("Bob"); // ทำไม่ได้
Student.getName(); // ทำไม่ได้

สรุป

ทุก methods ในภาษา Java ต้องทำงานใน Class
Static method เป็นสมาชิกของ class ในขณะที่ non static method เป็นสามาชิกของ objects
การส่งค่าของทุก method จะส่่งแบบ passed  by value ขณะที่ object จะส่งแบบ passed by reference

แบบฝึกหัด

เขียน method ชื่อ printFullName ของนักเรียนซึ่งแสดงชื่อนามสกุลนักเรียน


class Student {
    private String firstName;
    private String lastName;
    public Student(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    // พิมพ์ code ของคุณตรงนี้
}

public class Main {
    public static void main(String[] args) {
        Student[] students = new Student[] {
            new Student("Morgan", "Freeman"),
            new Student("Brad", "Pitt"),
            new Student("Kevin", "Spacey"),
        };
        for (Student s : students) {
            s.printFullName();
        }
    }
}


class Student {
    private String firstName;
    private String lastName;
    public Student(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public void printFullName(){
      System.out.println(firstName+" " +lastName);     
    }
}

public class Main {
    public static void main(String[] args) {
        Student[] students = new Student[] {
            new Student("Morgan", "Freeman"),
            new Student("Brad", "Pitt"),
            new Student("Kevin", "Spacey"),
        };
        for (Student s : students) {
            s.printFullName();
        }
    }
}

การเขียนโปรแกรม Java แบบ Loops

Loops

For

Loops for ประกอบด้วย 3 ส่วน

for (int i = 0; i < 3; i++) {}

ส่วนแรกคือ (int i = 0) จะทำงานเพียงครั้งเดียวตอนเข้าสู่คำสั่ง for
จากนั้นจะทำงานในส่วนที่ 2 (i < 3) เป็นเงื่อนเหมือนกับ if ถ้าเงื่อนไขเป็น จริง จะทำงานภายใน Loop
ถ้าเป็นเท็จก็จะจบ loop หรือออกจาก loop
เมื่อทำงานคำสั่งภายใน loop เสร็จหมด โปรแกรมจะมาทำงานในส่วนที่ 3 (i++) คือการเปลี่ยนแปลงค่าตัวแปรที่ใช้เป็นเงื่อนไข ซึ่งจากตัวอย่างจะวน 3 รอบ

ลำดับการทำงานของ for loop จะทำงานดังนี้

        int i = 0;
        i < 3 // 0 < 3 = true
              // Inside of loop
        i++ // i is now 1
        i < 3 // 1 < 3 = true
              // Inside of loop
        i++ // i is now 2
        i < 3 // 2 < 3 = true
              // Inside of loop
        i++ // i is now 3
        i < 3 // 3 < 3 = false
              // Loop is done...

เราสามารถลบส่วนที่ 1 กับ 3 มันยังทำงานได้อยู่และมันจะเหมือนกัน while loop


for (;i < 5;) {}

While


while (condition) {}

โปรแกรมจะทำงานในส่วนเงื่อนไข (Condition) ก่อน และจะทำงานใน loop ทุกครั้งที่เงื่อนไขเป็นจริงไปเรื่อย ๆจนกว่าจะเป็นเท็จ เท็จเมื่อไหร่จบเมื่อนั้น

ถ้าต้องการให้โปรแกรมทำงานใน loop หนึ่งรอบ ควรใช้ do .. while loop ซึ่งจะทำงานคำสั่งภายใน loop ก่อนเช็คเงื่อนไข ซึ่งตรงข้ามกับ while ที่เช็คก่อนถึงจะทำ มี syntax ดังนี้


do {

} while(condition);


Foreach

เป็นอีกเวอร์ชั่นของ for เมื่อเราต้องการใช้ข้อมูลภายใน Array ทุกตัวตามลำดับเราใช้ for each จะง่ายกว่า for 

public class Main {
    public static void main(String[] args) {
        int[] arr = {2, 0, 1, 3};
        for (int el : arr) {
            System.out.println(el);
        }
        
    }
}

เปรียบเทียบกับ for


public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 9, 9, 5};
        for (int i = 0; i < arr.length; i++) {
            int el = arr[i];
            System.out.println(el);
        }
        
    }
}


break and continue

เป็นตัวควบคุม loop เมื่อเราต้องการให้หยุด loop อย่างทันทีโดยไม่ต้องรอให้เงื่อนใน loop for เป็นเท็จให้ใช้ break


public class Main {
    public static void main(String[] args) {
        int i;
        for (i = 0; i < 5; i++) {
            if (i >= 2) {
                break;
            }
            System.out.println("Yuhu");
        }
        System.out.println(i);
        // Output:
        // Yuho
        // Yuho
        // 2
        
    }
}


ส่วน continue ถ้าเจอ continue เมื่อไหร่จะจบการวน ในรอบนั้นทันที ไม่ทำงานในคำสั่งที่เหลือ ไม่เหมือน break ที่จบการทำงานของ loop ออกจาก loop ไปเลย


public class Main {
    public static void main(String[] args) {
        int i;
        for (i = 0; i < 5; i++) {
            if (i >= 3) {
                break;
            }
            System.out.println("Yuhu");
            if (i >= 1) {
                continue;
            }
            System.out.println("Tata");
        }
        System.out.println(i);
        // Output
        // Yuhu
        // Tata
        // Yuhu
        // Yuhu
        // 3
        

    }
}




แบบฝึกหัด


ใช้ loop แสดงข้อมูลใน Array numbers เฉพาะเลขคู่ ตามลำดับเดิม และไม่ต้องแสดงข้อมูลหลังจากเลข 237
public class Main {
    public static void main(String[] args) {
        int[] numbers = {
            951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 
            615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 
            386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 
            399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 
            815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 
            958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 
            743, 527};

        // พิมพ์ code ของคุณตรงนี้
    }
}

public class Main {
    public static void main(String[] args) {
        int[] numbers = {
            951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 
            615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 
            386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 
            399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 
            815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 
            958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 
            743, 527};

        // พิมพ์ code ของคุณตรงนี้
        for(int number : numbers){
            if(number % 2 ==0) System.out.print(number + " "); 
            if(number == 237) break;
        }
    }
}

Java Array

Java Arrays


การประกาศตัวแปร Array แบบไม่กำหนดขนาด

int[] arr;

แบบกำหนดขนาด array 10 ช่อง ชื่อ arr
arr = new int[10];

เราสามารถตรวจสอบขนาดของ array โดยพิมพ์ขนาดของ Array ใช่ method lenght

System.out.println(arr.length);

เราสามารถอ้างอิงตำแหน่งของ Array ได้

arr[0] = 4;
arr[1] = arr[0] + 5;
arr[1] จะเท่ากับ 9

เราสามารถกำหนดค่าใน Array ตั้งแต่ประกาศตัวแปรได้เลยโดยไม่ต้องระบุขนาด

int[] arr = {1, 2, 3, 4, 5};

แบบฝึกหัด

แก้ Error

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        int length = numbers[3];
        char[] chars = new char[length];
        chars[numbers.length + 4] = 'y';
        System.out.println("Done!");
    }
}

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        int length = numbers[0];
        char[] chars = new char[length];
        chars[numbers.length - 3] = 'y';
        System.out.println("Done!");
    }
}

การเปรียบแบบมีเงื่อนไข (Conditionals) if .. else

Conditionals if ..else if ...else


ภาษา Java ใช้ boolean ในการประเมินผลเงื่อนไข จะมีการคืนค่าเป็น จริง  true  กับ เท็จ  false  เท่านั้น

ตัวอย่าง

public class Main {
    public static void main(String[] args) {
        int a = 4;
        boolean b = a == 4;
        if (b) {
            System.out.println("It's true!");
        }
    
    }
}

หรือ
public class Main {
    public static void main(String[] args) {
        int a = 4;
        boolean b = a;
        if (b == 4) {
            System.out.println("It's true!");
        }
        
    }
}

Boolean operators

ตัวดำเนินการในการเปรียบเทียบที่ใช้บ่อย
public class Main {
    public static void main(String[] args) {
        int a = 4;
        int b = 5;
        boolean result;
        result = a < b; // true
        result = a > b; // false
        result = a <= 4 // a smaller or equal to 4 - true
        result = b >= 6 // b bigger or equal to 6 - false
        result = a == b // a equal to b - false
        result = a != b // a is not equal to b - true
        result = a > b || a < b // Logical or - true
        result = 3 < a && a < 6 // Logical and - true
        result = !result // Logical not - false
    }
}

if - else and between


เงื่อนไขแบบ if อย่างเดียว
public class Main {
    public static void main(String[] args) {
        if (a == b) {
            // a และ b เท่ากัน
        }       
    }
}

เงื่อนไขแบบ if ... else
public class Main {
    public static void main(String[] args) {
        if (a == b) {
            // ส่วนนี้เรารู้กันแล้ว
        } else {
            // a และ b ไม่เท่ากัน... :/
        } 
    }
}

ถ้า code ภายใน if หรือ else มีบรรทัดเดียวไม่ต้องใส่ {} ก็ได้
public class Main {
    public static void main(String[] args) {
        if (a == b) System.out.println("Yeah!");
        else System.out.println("Ohhh...");
    }
}

หรือ
public class Main {
    public static void main(String[] args) {
        if (a == b)
            System.out.println("Another line Wow!");
        else
            System.out.println("Double rainbow!");
    }
}

แนะนำ

มีอีกทางเลือกหนึ่งสำหรับการเขียน if...else ที่มีคำสั่งเดียว
public class Main {
    public static void main(String[] args) {
        int a = 4;
        int result = a == 4 ? 1 : 8; //ผลลัพจะเท่ากับ 1
    }
}

ผลลัพธ์เหมือนกันแต้ code ต่างกันมาก
public class Main {
    public static void main(String[] args) {
        int a = 4;
        int result;
        if (a == 4) {
            result = 1;
        } else {
            result = 8;
        }
    }
}

== and equals

การใช้ == จะใช้กับตัวแปร string ธรรมดาได้ แต่ถ้าเป็น object ต้องใช้ method equals() เพื่อเปรียบเทียบค่าใน object

public class Main {
    public static void main(String[] args) {
        String a = new String("Wow");
        String b = new String("Wow");
        String sameA = a;
        
        boolean r1 = a == b; // เป็นเท็จ, เป็นคนละ object
        boolean r2 = a.equals(b); // จริง, ข้อความใน object เหมือนกัน
        boolean r3 = a == sameA; // จริง, เป็น object เดียวกัน
        
    }
}

แบบฝึกหัด

แก้ไขโค้ดให้แสดงผลคำว่า Success! ให้ได้

public class Main {
    public static void main(String[] args) {
        String a = new String("Wow");
        String b = "Wow";
        String c = a;
        String d = c;

        boolean b1 = a == b;
        boolean b2 = b.equals(b + "!");
        boolean b3 = !c.equals(a);

        if (b1 && b2 && b3) {
            System.out.println("Success!");
        }
    }
}


public class Main {
    public static void main(String[] args) {
        String a = new String("Wow");
        String b = "Wow";
        String c = a;
        String d = c;

        boolean b1 = a.equals(b);
        boolean b2 = b.equals(b);
        boolean b3 = c.equals(a);

        if (b1 && b2 && b3) {
            System.out.println("Success!");
        }
    }
}