[Java]題目:統計各字元數量

Boom
May 19, 2021

--

<code>

package test;import java.util.Scanner;public class ex7 {public static void main(String[] args) {/*題目:輸入一行字元,分別統計出其英文字母、空格、數字和其它字元的個數。1.宣告變數(英文字母、空格、數字、其他..)2.設定條件3.輸出結果*一行字元要用字串接收,nextLine()*字串轉字元,查ASCII碼(如下)*英文(65–90,97–122)、空格(32)、數字(48–57)、其他(else)*/int eng=0;//英文字母int space=0;//空格int num=0;//數字int others=0;//其他字元Scanner input=new Scanner(System.in);System.out.println(“請輸入一行字元”);String s=input.nextLine();//接收字元//把字串丟到字元(char)陣列char[] str=s.toCharArray();//拿裡面的字元看是否在範圍內,並且做統計for(int i=0;i<str.length;i++){if(str[i]==32){space++;}else if((str[i]>=65&&str[i]<=90)||(str[i]>=97&&str[i]<=122)){eng++;}else if(str[i]>=48&&str[i]<=57){num++;}else{others++;}}//printSystem.out.printf(“英文:%d\n空格:%d\n數字:%d\n其他:%d\n”,eng,space,num,others);}}

<console>

--

--

Boom
Boom

Written by Boom

Boom Engineer | BOOM ⭐ 程式自學之旅 | 透過筆記釋放記憶體,記錄自己的程式筆記,『內化』成為這段旅程的養分,也分享給路過,正在經歷這趟旅程的你 | Java note begin at 2020.09 | Python note begin at 2021.03

No responses yet