ในบทความนี้ เราจะทำความเข้าใจวิธีตรวจสอบว่า ตัวอักษร (character) ที่ป้อนเข้ามาเป็นอัลฟาเบตหรือไม่ โดยตรวจสอบว่าอยู่ในช่วง 'a' ถึง 'z' หรือ 'A' ถึง 'Z'
ตัวอย่าง Input และ Output
Input:
Enter a character: H
Output:
The character H is an alphabet
อัลกอริธึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศตัวแปร char my_input ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น ขั้นตอนที่ 4 - ใช้ if-else ตรวจสอบว่า my_input อยู่ระหว่าง 'a'-'z' หรือ 'A'-'Z' ด้วย >= และ <= ขั้นตอนที่ 5 - แสดงผลลัพธ์ ขั้นตอนที่ 6 - หยุด
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class Alphabet {
public static void main(String[] args) {
char my_input;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined");
System.out.print("Enter the character : ");
my_input = my_scanner.next().charAt(0);
if ((my_input >= 'a' && my_input <= 'z') || (my_input >= 'A' && my_input <= 'Z'))
System.out.println("The character " + my_input + " is an alphabet");
else
System.out.println("The character " + my_input + " is not an alphabet");
}
}
Output
Required packages have been imported A reader object has been defined Enter the character : H The character H is an alphabet
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class Alphabet {
public static void main(String[] args) {
char my_input;
my_input = 'H';
System.out.println("The Alphabet is defined as " + my_input);
if ((my_input >= 'a' && my_input <= 'z') || (my_input >= 'A' && my_input <= 'Z'))
System.out.println("The character " + my_input + " is an alphabet.");
else
System.out.println("The character " + my_input + " is not an alphabet.");
}
}
Output
The Alphabet is defined as H The character H is an alphabet.