該程序應該只輸出一個字符串中的一個字符,然後指定該字符串中的出現次數。它應該按升序排列,具體取決於特定字符的出現次數。它的工作除了在(char)i
部分。它與ASCII代碼或什麼有關?
輸出一個字符串中的一個字符c#
所需的輸出:
B:1
d:1
一個:2個
S:2
代碼的輸出:
U:1
Y:1
þ:2
ÿ:2
public class HuffmanCode {
static String string;
static Scanner input = new Scanner(System.in);
public static void main(String args[]){
System.out.print("Enter a string: ");
string = input.nextLine();
int count[] = countOccurence(string);
Arrays.sort(count);
for (int i = 0; i < count.length; i++) {
if (count[i] > 0)
System.out.println((char)i + ": " + count[i]);
}
}
public static int[] countOccurence(String str){
int counts[] = new int[256];
for(int i=0;i<str.length();i++){
char charAt = str.charAt(i);
counts[(int)charAt]++;
}
return counts;
}
}
刪除'Arrays.sort(計數);' – saka1029
@ saka1029我想將它按升序排序。我應該只是硬編碼的排序,所以它會工作? – Meryel
您需要一個包含char和count的對象,創建一個List並對Lis進行排序。順便說一下:它是java,而不是c#,不是嗎? – Turo