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

要理解此示例,您应了解以下Java编程主题


示例 1: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 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。类似地,字母 A 存储为 65,字母 Z 存储为 90

现在,当我们比较变量 c 是否在 'a' 到 'z' 和 'A' 到 'Z' 之间时,变量会分别与字母 97 到 122 和 65 到 90 的 ASCII 值进行比较。

由于 * 的 ASCII 值不在字母的 ASCII 值范围内。因此,程序输出 * 不是字母


您也可以使用 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 语句被三元运算符(? :)替换了。


示例 3:Java 程序使用 isAlphabetic() 方法检查字母

class Main {
  public static void main(String[] args) {

    // declare a variable
    char c = 'a';

    // checks if c is an alphabet
    if (Character.isAlphabetic(c)) {
      System.out.println(c + " is an alphabet.");
    }
    else {
      System.out.println(c + " is not an alphabet.");
    }
  }
}

输出

a is an alphabet.

在上面的示例中,请注意表达式,

Character.isAlphabetic(c)

这里,我们使用了 Character 类的 isAlphabetic() 方法。如果指定的变量是字母,它将返回 true。因此,将执行 if 块内的代码。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战