題目:輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。
程序分析:利用while語句,條件為輸入的字符不為 '\n '.
1 package com.li.FiftyAlgorthm; 2 3 import java.util.Scanner; 4 5 /** 6 * 題目:輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。 7 * 8 * 程序分析:利用while語句,條件為輸入的字符不為 '\n ' 9 * @author yejin 10 */ 11 public class CharacterStatistics { 12 static int digital = 0; 13 static int character = 0; 14 static int other = 0; 15 static int blank = 0; 16 17 public static void main(String[] args) { 18 char[] ch = null; 19 Scanner sc = new Scanner(System.in); 20 String s = sc.nextLine(); 21 ch = s.toCharArray(); 22 23 for (int i = 0; i < ch.length; i++) { 24 if (ch[i] >= '0' && ch[i] <= '9') { 25 digital++; 26 } else if ((ch[i] >= 'a' && ch[i] <= 'z') || ch[i] > 'A' 27 && ch[i] <= 'Z') { 28 character++; 29 } else if (ch[i] == ' ') { 30 blank++; 31 } else { 32 other++; 33 } 34 35 } 36 System.out.println("數字個數: " + digital); 37 System.out.println("英文字母個數: " + character); 38 System.out.println("空格個數: " + blank); 39 System.out.println("其他字符個數:" + other); 40 } 41 }