到目前为止,这是我的方法。我试图在一个名为in.txt的文件中计算一个A字母。
public void countFile() {
BufferedReader reader;
int counter=0;
try {
reader = new BufferedReader(new FileReader("in.txt"));
}
catch(IOException ioException) {
System.err.println("Error Opening File: Terminating");
System.exit(1);
}
int data = reader.read();
while(data != -1) {
char charToSearch = 'A';
//this is the part i mess up and i dont know how to fix it the char data have to be int and the char to search is char.
if(charToSearch = (char) data); {
counter++;
}
};
reader.close();
System.out.println(counter);
}
谢谢你帮助我。我一直在努力,但我无法解决它。
答案 0 :(得分:0)
除了@ajb和@thegauravmahawar提到的if
问题之外,我们还需要正确处理异常。此外,我们需要处理while循环以正确读取BufferedReader,如@ajb所示。这是代码:
public void countFile() {
BufferedReader reader;
int counter = 0;
try {
reader = new BufferedReader(new FileReader("in.txt"));
int data;
while ((data = reader.read()) != -1) {
char charToSearch = 'A';
if (charToSearch == (char) data) {
counter++;
}
}
reader.close();
System.out.println(counter);
} catch (IOException ioException) {
System.err.println("Error Opening File: Terminating");
System.exit(1);
}
}