我正在编写一个程序来计算该数字在 twxt 文件中出现的次数。文本的输入是在运行时给出的。输入存储在文本文件中,现在我必须计算频率并将结果输出到另一个文本文件中。
import java.io.File;
import java.util.Formatter;
import java.util.Scanner;
public class StudentPoll
{
private Scanner x;
int[] frequency = new int[5];
int count =0;
public void openFile(){
try{
x = new Scanner(new File("numbers.txt"));
}
catch(Exception e){
System.out.printf("No File found");
}
}
public void readFile(){
while(x.hasNext()){
int a= x.nextInt();
if(a==1){
frequency[0]=0;
++frequency[0];
break;
}
else if (a== 2){
frequency[1]=0;
++frequency[1];
break;
}
else if( a==3){
frequency[2]=0;
++frequency[2];
break;
}
else if (a==4){
frequency[3]=0;
++frequency[3];
break;
}
else if (a== 5){
frequency[4]=0;
++frequency [4];
break;
}
}
System.out.printf("%s%10s\n","Rating","Frequency");
System.out.printf("%s%10s\n","1",++frequency[0]);
System.out.printf("%s%10s\n","2",++frequency[1]);
System.out.printf("%s%10s\n","3",++frequency[2]);
System.out.printf("%s%10s\n","4",++frequency[3]);
System.out.printf("%s%10s\n","5",++frequency[4]);
}
}
public void closeFile(){
x.close();
}
我应该得到输出:
Rating Frequency
1 1
2 2
3 1
4 1
5 1
但是频率计数不正确。我不知道我在这里犯了什么错误。
我也不知道如何将此输出写入另一个文件。我需要改变什么?