Java 程式檢查輸入的字元是數字、空白、小寫字母還是大寫字母


要檢查輸入的字元是數字、空格、小寫字母還是大寫字母,您需要檢查它們的 ASCII 值。

假設我們有一個要檢查的值儲存在變數 “val” 中。

對於小寫字母。

if(val >= 97 && val <= 123) {
   System.out.println("Lower Case");
}

對於大寫字母

else if(val >= 65 && val <= 96) {
   System.out.println("Upper Case");
}

對於數字

else if(val >= 48 && val <= 57) {
   System.out.println("Digit");
}

現在檢查空格

else if(Character.isWhitespace(val)) {
   System.out.println("Whitespace");
}

以下是完整的示例。

示例

 即時演示

public class Demo {
   public static void main(String []args) {
      char val ='L';
      System.out.println("Given Value: "+val);
      if(val >= 97 && val <= 123) {
         System.out.println("Lower Case");
      } else if(val >= 65 && val <= 96) {
         System.out.println("Upper Case");
      } else if(val >= 48 && val <= 57) {
         System.out.println("Digit");
      } else if(Character.isWhitespace(val)) {
         System.out.println("Whitespace");
      }
   }
}

輸出

Given Value: L
Upper Case

讓我們看另一個示例。

示例

public class Demo {
   public static void main(String []args) {
      char val ='L';
      System.out.println("Given Value: "+val);
      if(val >= 97 && val <= 123) {
         System.out.println("Lower Case");
      } else if(val >= 65 && val <= 96) {
         System.out.println("Upper Case");
      } else if(val >= 48 && val <= 57) {
         System.out.println("Digit");
      } else if(Character.isWhitespace(val)) {
         System.out.println("Whitespace");
      }
   }
}

輸出

Given Value: a
Lower Case

更新日期:26-6-2020

861 次瀏覽

開啟您的職業生涯

完成課程認證

開始
廣告