Part1 -> Section1 -> Basic -> 008. The if statement

     if statement คือโค้ดบล็อกที่ใช้เลือกเงื่อนไข ซึ่ง if ต้องการ boolean เป็น input (มีแค่ true และ false) ลองศึกษาเพิ่มจากตัวอย่าง

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

            Console.WriteLine("Please enter a number 0 to 10");
            input = int.Parse(Console.ReadLine());

            if (input > 10)
            {
                Console.WriteLine("You enter a number more than 10");
            }
            else if (input > 0)
            {
                Console.WriteLine("Good job");
            }
            else
            {
                Console.WriteLine("You enter a negative number");
            }
        }
    }
}

     ตัวอย่างนี้แสดงการใช้งาน if statement เป็นโปรแกรมที่รับตัวเลขมาแล้วเช็คเงื่อนไขเพื่อแสดงคำอธิบายตัวเลขนั้นๆ ในตัวอย่างคือ

ถ้าใส่ตัวเลขเกิน 10 โปรแกรมจะแสดงข้อความว่า You enter a number more than 10
ถ้าใส่ตัวเลขมากกว่า 0 โปรแกรมจะแสดงข้อความว่า Good job
นอกเหนือจากนั้นโปรแกรมจะแสดงข้อความว่า You enter a negative number

     นอกจากนี้เราสามารถใช้เงื่อนไขแบบคอมโบได้ ตัวอย่างด้านล่าง

if (input <= 10 && input >= 0)
            {
                Console.WriteLine("Good job");
            }
            else
            {
                Console.WriteLine("Please enter a number 0 to 10");
            }

     รวมสองเงื่อนไขไว้ที่เดียวกันเลย โดยจะคั่นแต่ละเงื่อนไขด้วย logical operator ก็มี & (and) และ | (or) ที่เราเคยเรียนมาตั้งแต่ชั้นมัธยมนะครัช ซึ่งโปรแกรมทั้งสองทำงานได้ผลลัพธ์เหมือนกันแค่เขียนกันคนละแบบ

สอบถามหรือติดตามได้ที่ https://www.facebook.com/learnaspnetmvcjquery

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

Part2 -> Section1 The Basic -> 003. MVC Folder Structure

Part2 -> Section1 The Basic -> 001. Introduction

Part2 -> Section1 The Basic -> 005. Controller