Java小程序:随意输入一些字符,统计每个字符出现的次数
程序运行截图:
代码:
public class StringDemo {
public static void main(String[] args) {
StringDemo localDemo = new StringDemo();
localDemo.InputAndOutput();
}
/**
* Java的标准输入/输出
*/
private void InputAndOutput() {
byte[] buffer = new byte[512];
System.out.println();
try {
System.out.print("请输入:");
int count = System.in.read(buffer);// 返回实际读取的字节数
System.out.println();
System.out.print("您输入的字符:");
byte[] bts = new byte[count - 1];
for (int i = 0; i < count - 1; i++) {
System.out.print((char) buffer[i]);
bts[i] = buffer[i];
}
System.out.println();
// 对bts排序,根据ASCII值由小到大排序
bubbleSort(bts);
int num = 1;
byte bt = bts[0];
for (int i = 1; i <= bts.length; i++) {
if(i == bts.length) {
System.out.println((char) bt + "出现了" + num + "次");
} else if (bt == bts[i]) {
num++;
} else {
System.out.println((char) bt + "出现了" + num + "次");
bt = bts[i];
num = 1;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 冒泡排序
*
* 由小到大排序
*
* 从后向前冒泡
*
* @param arr
*/
public void bubbleSort(byte[] arr) {
if (arr == null || arr.length == 0)
return;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = arr.length - 1; j > i; j--) {
if (arr[j] < arr[j - 1]) {
swap(arr, j - 1, j);
}
}
}
}
public void swap(byte[] arr, int i, int j) {
byte temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}