Skip to content

Latest commit

 

History

History
64 lines (41 loc) · 1.69 KB

File metadata and controls

64 lines (41 loc) · 1.69 KB

Java 程序:检查字符是否为字母

原文: https://www.programiz.com/java-programming/examples/alphabet

在此程序中,您将学习检查给定字符是否为字母。 这是使用 Java 中的if else语句或三元运算符完成的。

示例:使用if-else代码检查字母的 Java 程序

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 中使用三元运算符解决问题。

示例 2:使用三元运算符检查字母的 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语句被三元运算符(? :)代替。