1 package JavaDemo; 2 import java.util.Scanner; 3 /* 4 題目: 5 鍵盤輸入一個字符串,並且統計其中各種字符出現的次數。 6 種類有:大寫字母,小寫字母,數字,其他 7 */ 8 public class WorkDemo02 { 9 public static void main(String[] args) { 10 Scanner sc = new Scanner(System.in); 11 System.out.println("請輸入一個字符串:"); 12 String input = sc.next();//獲取一個字符串 13 14 //計數器 15 int countUpper = 0; //大寫字母 16 int countLower = 0; //小寫字母 17 int countNumber = 0;//數字 18 int countOther = 0; //其他 19 //將字符串轉換為字符數組 20 char[] charArray = input.toCharArray(); 21 for (int i = 0; i < charArray.length; i++) { 22 char ch = charArray[i];//當前單個字符 23 if ('A' <= ch && ch <= 'Z') { 24 countUpper++; //大寫字母 25 } else if ('a' <= ch && ch <= 'z') { 26 countLower++; 27 } else if ('0' <= ch && ch <= '9') { 28 countNumber++; 29 } else { 30 countOther++; 31 } 32 } 33 System.out.println("大寫字母有:"+countUpper); 34 System.out.println("小寫字母有:"+countLower); 35 System.out.println("數字寫字母有:"+countNumber); 36 System.out.println("其他字母有:"+countOther); 37 } 38 }