思路:簡單的利用一個多重 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);
}
}
新聞熱點
疑難解答