1. 程式人生 > >21天刷題計劃之10.1—統計大寫字母個數(Java語言描述)

21天刷題計劃之10.1—統計大寫字母個數(Java語言描述)

題目描述:

找出給定字串中大寫字元(即’A’-‘Z’)的個數
介面說明
原型:int CalcCapital(String str);
返回值:int

輸入描述:

輸入一個String資料

輸出描述:

輸出string中大寫字母的個數

示例1

輸入
add123#$%#%#O

輸出
1

分析:

獲取輸出的字串,將字串轉換成字元陣列,遍歷字元陣列並判斷是否為大寫字母即可。

import java.util.Scanner;

public class Main {

	public static void main(String[] args) throws Exception {
		
		Scanner scan = new Scanner(System.in);
		
		while(scan.hasNext()){
			String str = scan.next();
			System.out.println(CalcCapital(str));
		}

	}

	public static int CalcCapital(String str) throws Exception {
		
		if(str == null || str.length() == 0){
			throw new Exception("輸入有誤!!!");
		}
		char[] ch = str.toCharArray();
		int count = 0;
		for(int i = 0 ; i < ch.length ; i++){
			if(ch[i]>='A' && ch[i]<='Z'){
				count++;
			}
		}
		return count;
	}

}