English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此程序中,您将学习检查给定字符是否为字母。这是使用Java中的if...else语句或三元运算符完成的。
public class Alphabet { public static void main(String[] args) { char c = '';*'; if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ) System.out.println(c + " is a letter."); else System.out.println(c + " is not a letter."); } }
Output result
* Not a letter.
In Java, a char variable stores the ASCII value of a character (from 0 to127between the numbers) rather than the characters themselves.
The ASCII values of lowercase letters start from97to122. The ASCII values of uppercase letters start from65to90. That is, the letter a is stored as97, the letter z as122. Similarly, the letter A is stored as65, the letter Z as90。
Now, when comparing the variable c between 'a' and 'z' and between 'A' and 'Z', we store the letter97to122,65to9The ASCII value of 0 is compared
Since*The ASCII value does not fall between the ASCII values of letters. Therefore, the program output * Not a letter。
您也可以在Java中使用三元运算符解决问题。
public class Alphabet { public static void main(String[] args) { char c = 'A'; String output = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); ? c + "C'est une lettre." : c + " is not a letter. "; System.out.println(output); } }
Output result
A is a letter.
In the above program, the if-else statement is replaced by the ternary operator (? :).
class Main { public static void main(String[] args) { //Declare a variable char c = 'a'; //Check if c is a letter if (Character.isAlphabetic(c)) { System.out.println(c + " is a letter."); } else { System.out.println(c + " is not a letter."); } } }
Output result
a is a letter.
In the above example, please note the following expression:
Character.isAlphabetic(c)
Here, we use the Character class's isAlphabetic() method. If the specified variable is a letter, it returns true. Therefore, the code in the if block is executed