English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestion des exceptions Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

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

Java examples summary

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

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

Example2:使用三元运算符检查字母的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 (? :).

Example3: Java program uses the isAlphabetic() method to check for letters

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

Java examples summary