0
我正在處理一個問題,我必須計算文本中字符的頻率。我沒有編碼,有點生疏,所以我認爲這將有助於我的代碼第二雙眼睛。 我的代碼在一個文件中讀取,理想情況下,它應該打我的if語句並將「1」添加到我的頻率數組中。但是,它總是打印「0」。我沒有正確添加?使用整數添加數組索引
public class hw4{
public static void main (String []args)throws IOException{
//ask user to enter file name
System.out.printf("Enter a file location and name to encode [press Enter]: ");
Scanner input = new Scanner(System.in);
String filename = input.next();
//Gets file name from Scanner and checks to see if valid
File file = new File(filename);
Scanner text = new Scanner(file);
String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
int[] freq = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
String letter;
while(text.hasNext()){
letter = text.next();
if (letter == "a"){
freq[0] = freq[0] + 1;
}
if (letter == "b"){
freq[1] = freq[1] + 1;
}
if (letter == "c"){
freq[2] = freq[2] + 1;
}
if (letter == "d"){
freq[3] = freq[3] + 1;
}
if (letter == "e"){
freq[4] = freq[4] + 1;
}
if (letter == "f"){
freq[5] = freq[5] + 1;
}
if (letter == "g"){
freq[6] = freq[6] + 1;
}
if (letter == "h"){
freq[7] = freq[7] + 1;
}
if (letter == "i"){
freq[8] = freq[8] + 1;
}
if (letter == "j"){
freq[9] = freq[9] + 1;
}
if (letter == "k"){
freq[10] = freq[10] + 1;
}
if (letter == "l"){
freq[11] = freq[11] + 1;
}
if (letter == "m"){
freq[12] = freq[12] + 1;
}
if (letter == "n"){
freq[13] = freq[13] + 1;
}
if (letter == "o"){
freq[14] = freq[14] + 1;
}
if (letter == "p"){
freq[15] = freq[15] + 1;
}
if (letter == "q"){
freq[16] = freq[16] + 1;
}
if (letter == "r"){
freq[17] = freq[17] + 1;
}
if (letter == "s"){
freq[18] = freq[18] + 1;
}
if (letter == "t"){
freq[19] = freq[19] + 1;
}
if (letter == "u"){
freq[20] = freq[20] + 1;
}
if (letter == "v"){
freq[21] = freq[21] + 1;
}
if (letter == "w"){
freq[22] = freq[22] + 1;
}
if (letter == "x"){
freq[23] = freq[23] + 1;
}
if (letter == "y"){
freq[24] = freq[24] + 1;
}
if (letter == "z"){
freq[25] = freq[25] + 1;
}
}
for(int i=0; i <26; i++){
System.out.printf("%s:%d\n", letters[i], freq[i]);
}
}
}
你需要指定哪些這是一種語言,這會非常顯着地影響答案。 – akronymn