java实现统计输入一行string中统计其中各个字符出现的次数

2023-05-16

方法:通过数组ArrayList实现

代码包括两个文件

1)     保存统计的字符和其出现次数的对象1

package codeSHP;

public class Object01 {
    char c;
    int count;
    public Object01(char c, int count ){
        this.c= c;
        this.count=count;
    }
}

2)     主程序


package codeSHP;

import java.util.ArrayList;
import java.util.Scanner;

//计算输入的每个字符出现的次数
public class RateNum {

	private void countNum(String str) {
		ArrayList<Object01> al = new ArrayList<Object01>();
		//System.out.println("size :"+al.size());
		//Object01 obj = null;
		for (int i = 0; i < str.length(); i++) {		//将string拆成一个一个char类型的字符
			char c = str.charAt(i);
			int count = 1;			//默认的出现的次数为1
			if(al.size()==0){			//输入第一个字符
				al.add(new Object01(c, count));
			}else{				//每输入一个新的字符都需要和前面的字符一一比较
				int flag=0;
				for(int j=0;j<al.size();j++){
					Object01 obj1 = (Object01) al.get(j);
					char c1 = obj1.c;
					int count1 = obj1.count;
					//System.out.println(c1 + " " + count1);
					if(c==c1){		//如果该字符在数组中出现,将该字符对应的次数加1 ,更新该字符的数据,并跳出循环
						count1++;
						flag=1;
						al.remove(obj1);
						al.add(new Object01(c,count1));
						break;
					}
				}
				if(flag==0){	//如果以上循环没有找到相同字符,将新的字符加入数组
					al.add(new Object01(c,count));
				}
			}
		}
		
		//输出结果
		for (int k = 0; k < al.size(); k++) {	
			Object01 obj2 = (Object01) al.get(k);
			System.out.println(obj2.c + " appear: " + obj2.count + " times ");
		}

	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter string :");
		String s = sc.nextLine();
		new RateNum().countNum(s);
	}

}

3) 运行结果: 空格也作了统计

Enter string :System.out.print("Enter string :");
S appear: 1 times
y appear: 1 times
m appear: 1 times
o appear: 1 times
u appear: 1 times
. appear: 2 times
p appear: 1 times
( appear: 1 times
E appear: 1 times
e appear: 2 times
s appear: 2 times
t appear: 5 times
r appear: 3 times
i appear: 2 times
n appear: 3 times
g appear: 1 times
  appear: 2 times
: appear: 1 times
" appear: 2 times
) appear: 1 times
; appear: 1 times





本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java实现统计输入一行string中统计其中各个字符出现的次数 的相关文章

随机推荐