- package wordscount;
- /**
- *
- * @author RaywayJohn ----该程序为让用户输入字符串,并统计其中各个字符出现的次数
- */
- import java.util.*;
- public class Words
- {
- String str;
- public Words( String str)
- {
- this.str=str;
- }
- public int count(char key)//计算某个字符是否在该字符串中,如果在返回出现的个数,如果不在,返回-1
- {
- int i=0;
- int temp=0;
- if(str.indexOf(key)!=-1)
- {
- for(i=str.indexOf(key);i<=str.lastIndexOf(key);i++)
- {
- if(key==str.charAt(i))
- temp=temp+1;
- }
- return temp;
- }
- else return -1;
- }
- public static void main(String[] args)
- {
- System.out.print("请输入字符串(可包含空格):");
- Scanner input=new Scanner(System.in);
- Words wordsEng=new Words(input.nextLine());
- int i=0;
- int j=0;
- int k=0;
- int temp=0;
- char tempChar[]=new char[wordsEng.str.length()];//该tempChar为保存之前计算过出现次数的某个字符
- char backSpace=32;
- tempChar[0]=wordsEng.str.charAt(0);
- a: for(i=0;i<wordsEng.str.length();i++)
- {
- b: for(j=0;j<i;j++)
- {
- if(tempChar[j]==wordsEng.str.charAt(i))//如果之前已经出现过该字符,那么不打印,如果没有出现过,则打印
- continue a;
- else continue b;
- }
- if(wordsEng.str.charAt(i)!=32)//判断该字符受否为空格
- System.out.println(wordsEng.str.charAt(i)+"出现的次数为:"+wordsEng.count(wordsEng.str.charAt(i)));
- else
- System.out.println("空格出现的次数为:"+wordsEng.count(wordsEng.str.charAt(i)));
- tempChar[k++]=wordsEng.str.charAt(i);
- }
- }
- }
转载于:https://blog.51cto.com/raywayjohn/759956