我正在解决一个问题,我必须计算文本中字符的频率。我有一段时间没写代码了,有点生疏了,所以我认为再看一眼我的代码会有所帮助。我的代码读入一个文件,理想情况下它应该命中我的 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]);
}
}
}