輸入一行字符,統計其中字母、數字、空格、其它字符的數量,並輸出到控制檯

輸入一行字符,統計其中字母、數字、空格、其它字符的數量,並輸出到控制檯

package String;

import java.util.Scanner;

public class numbersCount {

public static void main(String[] args) {
    // TODO 自動生成的方法存根
    Scanner sc = new Scanner(System.in);
    System.out.println("請輸入您要統計的字符串:(按回車鍵結束輸入)");
    String str = sc.nextLine();
    int letterCount=0,numberCount=0,spaceCount=0,otherCount=0;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if(c<='z'&&c>='a'||c<='Z'&&c>='A') {
            letterCount++;
        }else if(c<='9'&&c>='0'){
            numberCount++;
        }else if(c==' '){ 
            spaceCount++;
        }else{
            otherCount++;
        }

    }
    System.out.println("字母有"+letterCount+"個");
    System.out.println("數字有"+numberCount+"個");
    System.out.println("空格有"+spaceCount+"個");
    System.out.println("其它有"+otherCount+"個");

    }
}

以上是正確的,下面我貼出一組錯誤代碼,有興趣的分析下以下代碼錯在了哪裏,爲什麼錯了
package String;

import java.util.Scanner;

public class numbersCount {

public static void main(String[] args) {
    // TODO 自動生成的方法存根
    Scanner sc = new Scanner(System.in);
    System.out.println("請輸入您要統計的字符串:(按回車鍵結束輸入)");
    String str = sc.nextLine();
    int letterCount=0,numberCount=0,spaceCount=0,otherCount=0;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if(c<='z'&&c>='a'||c<='Z'&&c>='A') letterCount++;
        if(c<='9'&&c>='0') numberCount++;
        if(c==' '){ 
            spaceCount++;
        }else{
            otherCount++;
        }

    }
    System.out.println("字母有"+letterCount+"個");
    System.out.println("數字有"+numberCount+"個");
    System.out.println("空格有"+spaceCount+"個");
    System.out.println("其它有"+otherCount+"個");

}
}

答:錯在了otherCount,因爲上述代碼是把除空格外的所有字符都進行統計,包括了字母和數字,而題目要求是不要字母和數字統計到其它裏面的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章