1. ลำดับของifข้อความ
บางครั้งโปรแกรมจำเป็นต้องดำเนินการหลายอย่างขึ้นอยู่กับค่าของตัวแปรหรือค่าของนิพจน์
สมมติว่างานของเราเป็นดังนี้:
- หากอุณหภูมิสูงกว่า
20องศาให้ใส่เสื้อ - หากอุณหภูมิสูงกว่า
10องศาและน้อยกว่า (หรือเท่ากับ)20ให้สวมเสื้อกันหนาว - หากอุณหภูมิสูงกว่า
0องศาและน้อยกว่า (หรือเท่ากับ)10ให้ใส่เสื้อกันฝน - หากอุณหภูมิต่ำกว่า
0องศาให้ใส่เสื้อโค้ท
นี่คือวิธีที่สามารถแสดงเป็นรหัส:
int temperature = 9;
if (temperature > 20)
System.out.println("put on a shirt");
else // Here the temperature is less than (or equal to) 20
{
if (temperature > 10)
System.out.println("put on a sweater");
else // Here the temperature is less than (or equal to) 10
{
if (temperature > 0)
System.out.println("put on a raincoat");
else // Here the temperature is less than 0
System.out.println("put on a coat");
}
}
If-elseงบสามารถซ้อนกัน สิ่งนี้ทำให้สามารถใช้ตรรกะที่ค่อนข้างซับซ้อนในโปรแกรมได้
แต่ตัวอย่างข้างต้นก็น่าสนใจเช่นกัน ที่เราสามารถทำให้โค้ดง่ายขึ้นเล็กน้อยโดยไม่ใช้วงเล็บปีกกา:
int temperature = 9;
if (temperature > 20)
System.out.println("put on a shirt");
else // Here the temperature is less than (or equal to) 20
if (temperature > 10)
System.out.println("put on a sweater");
else // Here the temperature is less than (or equal to) 10
if (temperature > 0)
System.out.println("put on a raincoat");
else // Here the temperature is less than 0
System.out.println("put on a coat");
อย่างไรก็ตาม โปรแกรมเมอร์มักจะเขียนโครงสร้างนี้แตกต่างกันเล็กน้อย:
int temperature = 9;
if (temperature > 20)
System.out.println("put on a shirt");
else if (temperature > 10) // Here the temperature is less than (or equal to) 20
System.out.println("put on a sweater");
else if (temperature > 0) // Here the temperature is less than (or equal to) 10
System.out.println("put on a raincoat");
else // Here the temperature is less than 0
System.out.println("put on a coat");
ทั้งสามตัวอย่างนี้มีค่าเท่ากัน
2. ความแตกต่างของelseบล็อก
หากไม่ได้ใช้วงเล็บปีกกาในif-elseโครงสร้าง ให้elseอ้างอิงไปยังค่าก่อนหน้าที่ใกล้เคียงifที่สุด
ตัวอย่าง:
| รหัสของเรา | มันจะทำงานอย่างไร |
|---|---|
|
|
หากคุณดูรหัสทางด้านซ้าย ดูเหมือนว่าผลลัพธ์หน้าจอจะเป็น "คุณไม่ต้องทำงาน" แต่นั่นไม่ใช่กรณี ในความเป็นจริงelseบล็อกและคำสั่ง "คุณไม่ต้องทำงาน" จะเชื่อมโยงกับifคำสั่ง ที่สอง (ยิ่งใกล้)
ในโค้ดทางด้านขวา โค้ดที่เกี่ยวข้องifและelseจะถูกเน้นด้วยสีแดง นอกจากนี้ วงเล็บปีกกายังวางไว้อย่างชัดเจนซึ่งแสดงให้เห็นอย่างชัดเจนว่าจะดำเนินการใด สตริงที่คุณไม่ต้องทำงานไม่เคยแสดงเมื่อageมีค่ามากกว่า60?
3. ตัวอย่างการใช้if-elseคำสั่ง
เนื่องจากเราได้สำรวจif-elseข้อความนี้เป็นอย่างดีแล้ว ขอยกตัวอย่าง:
import java.util.Scanner;
public class Solution {
public static void main(String[] args)
{
Scanner console = new Scanner(System.in); // Create a Scanner object
int a = console.nextInt(); // Read the first number from the keyboard
int b = console.nextInt(); // Read the second number from the keyboard
if (a < b) // If a is less than b
System.out.println(a); // we display a
else // otherwise
System.out.println(b); // we display b
}
}
GO TO FULL VERSION