Java频率分类器
我目前正在用java编写一个频率分类器,我很难获得正确的输出。输出的频率旁边应该有正确的字符,但是字符没有按照频率排序。频率输出正确,但字符不正确。我不确定如何更改或优化我的代码。我不能使用任何java分类器来完成此任务。使用的示例输入是Java频率分类器,java,frequency,Java,Frequency,我目前正在用java编写一个频率分类器,我很难获得正确的输出。输出的频率旁边应该有正确的字符,但是字符没有按照频率排序。频率输出正确,但字符不正确。我不确定如何更改或优化我的代码。我不能使用任何java分类器来完成此任务。使用的示例输入是aaaaaabbccdd 4242&%%$#@,它应该输出 2 freq: 4 4 freq: 4 A freq: 4 b freq: 4 freq: 2 % freq: 2 & freq: 2
aaaaaabbccdd 4242&%%$#@
,它应该输出
2 freq: 4
4 freq: 4
A freq: 4
b freq: 4
freq: 2
% freq: 2
& freq: 2
c freq: 2
d freq: 2
# freq: 1
$ freq: 1
@ freq: 1
公共类主{
公共静态无效频率排序(char[]beta){
int size=beta.length;
int-cnt;
int l=0;
int-cntwo=0;
内部温度=0;
int hold=0;
char tempChar;
char-holdChar;
char charlie[]=新字符[256];
int countArray[]=新的int[256];
int-sortedArray[]=新int[256];
char charSorted[]=新字符[256];
字符增量[]=新字符[256];
//将beta数组分配给charlie。
对于(int i=0;i 对于(int i=0;i)您得到的输出是什么?您得到的输出是什么?
public class Main {
public static void frequencySort(char[] beta) {
int size = beta.length;
int cnt;
int l = 0;
int cnttwo = 0;
int temp = 0;
int hold = 0;
char tempChar;
char holdChar;
char charlie[] = new char[256];
int countArray[] = new int[256];
int sortedArray[] = new int[256];
char charSorted[] = new char[256];
char delta[] = new char[256];
//assign beta array to charlie.
for (int i = 0; i < size; i++) {
charlie[i] = beta[i];
}
// this loop will count frequencies and store them in countArray and it
//will store the characters in charlie.
for (int i = 0; i < size; i++) {
cnt = 0;
for (int j = 0; j < size; j++) {
if (j < i && charlie[i] == charlie[j]) {
break;
}
if (charlie[j] == charlie[i]) {
cnt++;
}
if (j == size - 1) {
countArray[i] = cnt;
delta[i] = charlie[i];
}
}
}
for( int i=0; i<countArray.length; i++ )
{
if (countArray[i] != 0)
countArray[l++] = countArray[i];
}
//Here i copied the countArray to the newArray and removed the zeros
from the
//original countArray.
int [] newArray = new int[256];
System.arraycopy( countArray, 0, newArray, 0, l );
size = newArray.length;
for (int i = 0; i < size; i++)
{
sortedArray[i] = 0;
charSorted[i] = '\0';
}
for (int j = 0; j<size; j++)
{
temp = 0;
tempChar = '\0';
for (int i = 0; i < size; i++)
{
if (newArray[i] > temp)
{
temp = newArray[i];
tempChar = delta[i];
hold = i;
}
}
sortedArray[j] = temp;
charSorted[j] = tempChar;
newArray[hold] = 0;
}
for (int i = 0; i < l; i++) {
System.out.println(charSorted[i] + " " + sortedArray[i]);
}
}
public static void main (String[]args){
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Character Sorter Program");
System.out.println("Please input a string to be sorted");
String orig = scanner.nextLine(); // User input of string
char[] charArray = orig.toCharArray(); // convert the original
string to a char array
frequencySort(charArray);
}
}