原文: https://www.programiz.com/java-programming/examples/alphabet
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 an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
}运行该程序时,输出为:
* is not an alphabet.在 Java 中,char变量存储字符的 ASCII 值(0 到 127 之间的数字)而不是字符本身。
小写字母的 ASCII 值从 97 到 122。大写字母的 ASCII 值从 65 到 90。
这就是原因,我们在'a'(97)与'z'(122)之间比较变量c。 同样,我们进行相同的操作以检查'A'(65)至'Z'(90)之间的大写字母。
您也可以在 Java 中使用三元运算符解决问题。
public class Alphabet {
public static void main(String[] args) {
char c = 'A';
String output = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
? c + " is an alphabet."
: c + " is not an alphabet.";
System.out.println(output);
}
}运行该程序时,输出为:
A is an alphabet.在上面的程序中,if else语句被三元运算符(? :)代替。