c# - ตัวดำเนินการ Operators, ชนิดข้อมูล Types, และตัวแปร Variables

12/19/2556 0 Comments

C# Operators, Types, and Variables


วัตถุประสงค์ของบทความนี้นะครับ
  • เข้าใจว่าตัวแปรคืออะไร
  • ชนิดของตัวแปรคืออะไร
  • ตัวดำเนินการคืออะไร
ตัวแปรและชนิดของข้อมูล Variables and Types

          ตัวแปรเป็นภาชนะเก็บข้อมูล คุณสามารถใส่ข้อมูลลงไปในตัวแปรและสามารถเรียกใช้ข้อมูลนั้นผ่านตัวแปรเมื่อต้องการ ความหมายของข้อมูลในตัวแปรนั้นจะถูกระบุได้จาก ชนิดข้อมูลของตัวแปร


1. ข้อมูลชนิดตรรกะ The Boolean Type

          การประกาศตัวแปร boolean จะใช้คำว่า bool ซึ่งจะเก็บค่าเพียง 2 ค่าเท่านั้นคือ true , false  ในภาษาอื่น เช่น ภาษา C, C++ สามารถใช้เลข 0 แทน false และเลข 1 แทน true ได้ ในภาษา C# จะไม่ได้ ในตัวอย่างที่ 1 เป็นการยกตัวอย่างการใช้เขียนโปรแกรม

ตัวอย่างที่ 1 แสดงค่าใน Boolean

using System;

class Booleans
{
    public static void Main()
    {
        bool content = true;
        bool noContent = false;

        Console.WriteLine("It is {0} that C# Station provides C# programming language content.", content);
        Console.WriteLine("The statement above is not {0}.", noContent);
    }
}

ผลลัพธ์


It is True that C# Station provides C# programming language content.
The statement above is not False. 


2. ชนิดข้อมูลตัวเลข Integral Types

          ในภาษา C# Integral Types เป็นหมวดของชนิดข้อมูลที่เป็นตัวเลขจำนวนเต็ม ทั้ง signed, unsigned, และข้อมูลตัวอักษร (char) ซึ่ง char เป็น Unicode character หาอ่านได้่ที่ http://www.unicode.org/

TypeSize (in bits)Range
sbyte8-128 to 127
byte80 to 255
short16-32768 to 32767
ushort160 to 65535
int32-2147483648 to 2147483647
uint320 to 4294967295
long64-9223372036854775808 to 9223372036854775807
ulong640 to 18446744073709551615
char160 to 65535

          ชนิดข้อมูลตัวเลขชุดนี้สามารถนำมาคำนวณทางคณิตศาสตร์ ยกเว้น Char คุณสามารถเลือกใช้ชนิดข้อมูลจากตารางข้างบนนี้ตามความเหมาะสมโดยพิารณาจากค่า Range ให้เหมาะสมกับโปรแกรมของคุณ

ตัวอย่างที่ 2 โปรแกรมจะ number1 และ number2 มาบวกกัน

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
                  int number1, number2;

                  Console.WriteLine("Please enter a number:");
                  number1 = int.Parse(Console.ReadLine());

                  Console.WriteLine("Thank you. One more:");
                  number2 = int.Parse(Console.ReadLine());

                  Console.WriteLine("Adding the two numbers: " + (number1 + number2));

                  Console.ReadLine();
        }
    }
}

3.ชนิดข้อมูลเลขทศนิยม Floating Point and Decimal Types

          ชนิดข้อมูลทศนิยมทั้ง float และ double จะถูกใช้แทนจำนวนจริง ส่วน decimal ส่วนมากใช้ในทาง financial หรือ money values.

TypeSize (in bits)precisionRange
float327 digits1.5 x 10-45 to 3.4 x 1038
double6415-16 digits5.0 x 10-324 to 1.7 x 10308
decimal12828-29 decimal places1.0 x 10-28 to 7.9 x 1028

          การใช้ชนิดข้อมูลทศนิยม ( Floating Point ) เรามันใช้เมื่อมีการหารหรือคำนวณเศษส่วนที่ค่าไม่ลงตัว ส่วนการคำนวณทางการเงิน decimal เป็นทางเลือกที่ดีที่สุด เพราะว่าเราสามารถหลีกเลี่ยงปัญหา rounding errors ได้

4. ข้อความ The string Type

          String เป็นกลุ่มของ Char ที่เรียงต่อกันเป็นข้อความ ตัวอักษรบางตัวพิมพ์ออกหน้าจอไม่ได้ แต่เรายังต้องการใช้มัน เพราะฉะนั้นในภาษา C# จึงมีกรณีพิเศษเมื่อต้องการใช้อักษรเหล่่านั้นโดยการใช้เครื่องหมาย '\'

Escape SequenceMeaning
\'Single Quote
\"Double Quote
\\Backslash
\0Null, not the same as the C# null value
\aBell
\bBackspace
\fform Feed
\nNewline
\rCarriage Return
\tHorizontal Tab
\vVertical Tab

ตัวอย่างที่ 3 การประกาศตัวแปร string และการใช้งานเบื้องต้น

          โปรแกรมจะแสดงชื่อและนามสกุลตามที่ประไว้ในตัวแปรชื่อ firstName และ lastName จากนั้นโปรแกรมจะรับชื่อและนามสกุลใหม่อีกครั้งและแสดงชื่อนามสกุลใหม่

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName = "John";
            string lastName = "Doe";

            Console.WriteLine("Name: " + firstName + " " + lastName);

            Console.WriteLine("Please enter a new first name:");
            firstName = Console.ReadLine();

            Console.WriteLine("New name: " + firstName + " " + lastName);

            Console.ReadLine();
        }
    }
}

5. ตัวดำเนินการ C# Operators

         เครื่องหมายในการคำนวณทางคณิตศาสตร์ต่างๆ ทั้งบวก ลบ คูณ หาร ตรรกะ ซึ่งจะต้องใช้ร่วมกับตัวแปรเพื่อหาผลลัพธ์ของสมการซึ่งแสดงตามตารางด้านล่างนี้แล้ว

Category (by precedence)Operator(s)Associativity
Primaryx.y  f(x)  a[x]  x++  x--  new  typeof  default  checked  unchecked delegateleft
Unary+  -  !  ~  ++x  --x  (T)xright
Multiplicative*  /  %left
Additive+  -left
Shift<<  >>left
Relational<  >  <=  >=  is asleft
Equality==  !=right
Logical AND&left
Logical XOR^left
Logical OR|left
Conditional AND&&left
Conditional OR||left
Null Coalescing??left
Ternary?:right
Assignment=  *=  /=  %=  +=  -=  <<=  >>=  &=  ^=  |=  =>right

ตัวอย่างโปรแกรมการใช้ operators ต่างๆ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;

class Unary
{
    public static void Main()
    {
        int unary = 0;
        int preIncrement;
        int preDecrement;
        int postIncrement;
        int postDecrement;
        int positive;
        int negative;
        sbyte bitNot;
        bool logNot;

        preIncrement = ++unary;
        Console.WriteLine("pre-Increment: {0}", preIncrement);

        preDecrement = --unary;
        Console.WriteLine("pre-Decrement: {0}", preDecrement);

        postDecrement = unary--;
        Console.WriteLine("Post-Decrement: {0}", postDecrement);

        postIncrement = unary++;
        Console.WriteLine("Post-Increment: {0}", postIncrement);

        Console.WriteLine("Final Value of Unary: {0}", unary);

        positive = -postIncrement;
        Console.WriteLine("Positive: {0}", positive);

        negative = +postIncrement;
        Console.WriteLine("Negative: {0}", negative);

        bitNot = 0;
        bitNot = (sbyte)(~bitNot);
        Console.WriteLine("Bitwise Not: {0}", bitNot);

        logNot = false;
        logNot = !logNot;
        Console.WriteLine("Logical Not: {0}", logNot);
    }
}

อธิบายโปรแกรม 

17    preIncrement = ++unary;
 ++unary  หมายถึง เพิ่มค่าในตัว unary ขึ้น 1 ก่อน แล้วจึงจะส่งค่าไปให้ preIncrement ดังนั้น preIncrement = 1

 20   preDecrement = --unary; 
--unary เหมือนบรรทัดที่ 17 แต่เป็นการลดค่าลง ดังนั้น preDecrement จึ่งเท่ากับ 0

23    postDecrement = unary--;
unary-- คือ ส่งค่าไปยัง preIncrement ก่อน แล้วจึงลดค่าลง 1 ทีหลัง ดังนั้น preIncrement = 0

26    postIncrement = unary++;
unary++ เหมือนกับบรรทัดที่ 23 แต่เป็นการเพิ่มค่าขึ้น 1

31        positive = -postIncrement;
32        Console.WriteLine("Positive: {0}", positive);
33
34        negative = +postIncrement;
35        Console.WriteLine("Negative: {0}", negative);
ส่วนนี้เป็นเหมือนกันคำนวณทางคณิตศาสตร์นั้นคือ ค่าลบ * ลบ = ค่าบวก, ค่าบวก*ลบ=ลบ
ซึ่งในบรรทัด 31 postIncrement = -1 ;  -(-1) = 1
และบรรทัด 34   postIncrement = -1 ;  +(-1) = -1

37       bitNot = 0;
38       bitNot = (sbyte)(~bitNot);
39       Console.WriteLine("Bitwise Not: {0}", bitNot);
บรรทัดที่ 38 (~bitNot) คือการกลับบิต จาก "00000000" = 0 เป็น "111111111" = -1

41      logNot = false;
42      logNot = !logNot;
43      Console.WriteLine("Logical Not: {0}", logNot);
บรรทัดที่ 42 !logNot คือการ NOT ทางตรรกะศาสตร์ คือการเปลี่ยนเป็นตรงข้ามคือ false -> true

ผลลัพธ์ที่ได้

pre-Increment: 1
pre-Decrement 0
Post-Decrement: 0
Post-Increment: -1
Final Value of Unary: 0
Positive: 1
Negative: -1
Bitwise Not: -1
Logical Not: true 


ตัวอย่างสุดท้าย

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System;

class Binary
{
    public static void Main()
    {
        int x, y, result;
        float floatresult;

        x = 7;
        y = 5;

        result = x+y;    // 7 + 5 = 12
        Console.WriteLine("x+y: {0}", result);

        result = x-y;    // 7 - 5 = 2
        Console.WriteLine("x-y: {0}", result);

        result = x*y;    // 7 * 5 = 35
        Console.WriteLine("x*y: {0}", result);

        result = x/y;     // 7 / 5 = 1 เพราะเป็นจำนวนเต็มหารจำนวนเต็ม = จำนวนเต็ม
        Console.WriteLine("x/y: {0}", result);

        floatresult = (float)x/(float)y;  // 7 / 5 = 1.4
        Console.WriteLine("x/y: {0}", floatresult);

        result = x%y;    // 7 % 5 = 2 เป็นการหารแล้วเอาเศษ 7 / 5 = 1 เศษ 2
        Console.WriteLine("x%y: {0}", result);

        result += x;    //หมายถึง result = result + x ;ดังนั้นจะได้ result = 2 + 7 = 9
        Console.WriteLine("result+=x: {0}", result);
    }
}

ผลลัพธ์ที่ได้

x+y: 12
x-y: 2
x*y: 35
x/y: 1
x/y: 1.4
x%y: 2
result+=x: 9

เขียนโปรแกรมภาษา C# Hello, World!

12/19/2556 0 Comments

C# Hello World Tutorial

          ถ้าคุณเคยศึกษาภาษาอื่นๆ มาจะรู้ว่าเราเริ่มต้นเขียนภาษาไหนก็ตามต้องเริ่มเขียนโปรแกรม Hello World! เป็นอันดับแรก ในส่วนนี้เป็นพื้นฐานสุดๆของภาษา C#  ไม่ต้องห่วงครับเราจะไม่อยู่ในส่วนนี้นานครับ และผมจะไม่พูดถึงการติดตั้งโปรแกรมนะครับ  มาดูตัวอย่างการเขียนโค้ด Hello World ในแบบต่างๆ กัน

ตัวอย่างที่ 1


// Hello1.cs
public class Hello1
{
   public static void Main()
   {
      System.Console.WriteLine("Hello, World!");
   }
}

ผลลัพธ์

Hello, World!

อธิบายโค้ด
  • method หลักทุกตัวต้องอยูในคลาส
  • ในคลาส System.Console จะมี method ชื่อ WriteLine อยู่ มีสามารถในการแสดงข้อความออกทางคอนโซลได้

ตัวอย่างที่ 2

          เพื่อง่ายต่อการเขียนคำสั่งแสดงผลทางหน้าจอในครั้งต่อไปเราสามารถเรียกใช้ System ได้ดังนี้

// Hello2.cs
using System;

public class Hello2
{
   public static void Main()
   {
      Console.WriteLine("Hello, World!");
   }
}

ตัวอย่างที่ 3

          ถ้าคุณต้องการพิมพ์ข้อมูลเข้าผ่านทาง Command Line เพียงแค่เปลี่ยนเพิ่ม Argument ใน method หลักตามที่แสดงด้านล่าง ซึ่งในตัวอย่างนี้จะนับและแสดงผล Argument ใน Command line

// Hello3.cs
// arguments: A B C D
using System;

public class Hello3
{
   public static void Main(string[] args)
   {
      Console.WriteLine("Hello, World!");
      Console.WriteLine("You entered the following {0} command line arguments:",
         args.Length );
      for (int i=0; i < args.Length; i++)
      {
         Console.WriteLine("{0}", args[i]); 
      }
   }
}

ผลลัพธ์

Hello, World!
You entered the following 4 command line arguments:
A
B
C
D

ตัวอย่างที่ 4

          การคืนค่า return code โดยเพิ่มคำสั่งตามตัวอย่างด้านล่างนี้เลย

// Hello4.cs
using System;

public class Hello4
{
   public static int Main(string[] args)
   {
      Console.WriteLine("Hello, World!");
      return 0;
   }
}

ผลลัพธ์

Hello, World!

ตัวอย่างที่ 5

          หากคุณรันโปรแกรมแล้วหน้าคอนโซลดับไปไม่ทันดูผลลัพธ์สามารถเพิ่มโค้ดได้ดังนี้


using System;

   class HelloWorld
   {
      static void Main(string[] args)
      {
         Console.WriteLine("Hello World");
         Console.ReadKey();
      }
   }




Compiling and Running with Arguments in Java

12/19/2556 0 Comments

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

12/19/2556 0 Comments

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)

12/19/2556 0 Comments

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

12/18/2556 0 Comments

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;
        }
    }
}