輸入任意長的一個字符串,統計其字母、數字、空格及其他字符的數量。


  思路:簡單的利用一個多重 if 結構就可以解決。

 

  CODE:

import java.util.Scanner;

public class Character{
  public static void main(String[] args){
    System.out.println ("請輸入一個字符串:");
    Scanner ss = new Scanner(System.in);
    String sc = ss.nextLine();
    char[] ch= sc.toCharArray(); //字符串變成字符數組
    int abccount = 0;
    int numcount = 0;
    int spacecount = 0;
    int othercount = 0;
    for (int i = 0;i<sc.length();i++){
      if(ch[i]<='9'&&ch[i]>='0'){
        numcount++;
      }else if((ch[i]<='z'&&ch[i]>='a')||(ch[i]<='Z'&&ch[i]>='A')){
        abccount++;
      }else if(ch[i]==' '){
        spacecount++;
      }else{
        othercount++;
      }
    }
    System.out.println ("數字的個數為:"+numcount);
    System.out.println ("字母的個數為:"+abccount);
    System.out.println ("空格的個數為:"+spacecount);
    System.out.println ("其他字符個數為:"+othercount);
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM