1 package demo; 2 import java.util.Scanner; 3 /** 4 * 統計一個字符串中英文字母、空格、數字和其它字符的個數 5 */ 6 public class Statistics1 { 7 public static void main(String[]args){ 8 int i; 9 int LetterCount = 0; 10 int SpaceCount = 0; 11 int NumberCount = 0; 12 int OtherCount = 0; 13 14 //輸入一個字符串 15 Scanner in = new Scanner(System.in); 16 System.out.println("請輸入一個字符串:"); 17 String str = in.nextLine(); 18 19 //字符串轉換成字符數組 20 char[]ch = str.toCharArray(); 21 for(i = 0; i<str.length();i++){ 22 if(Character.isLetter(ch[i])){ 23 LetterCount++; 24 }else if(Character.isSpaceChar(ch[i])){ 25 SpaceCount++; 26 }else if(Character.isDigit(ch[i])){ 27 NumberCount++; 28 } 29 else{ 30 OtherCount++; 31 } 32 } 33 34 System.out.println("字符的個數為:"+LetterCount); 35 System.out.println("空格的個數為:"+SpaceCount); 36 System.out.println("數字的個數為:"+NumberCount); 37 System.out.println("其他字符個數為:"+OtherCount); 38 } 39 }