该程序需要计算并显示指定的charector出现在文本文件中的次数。
目前总转向了零。 我不是,如果我应该使用不同的循环,我还用“for”循环尝试。
// Hold user input and sum
String fileName; // Holds the name of the file
String letter; // Letter to search for in the file
int total = 0; // Holds the total number of characters in the file
// Get the name of the file and character from the user
fileName = JOptionPane.showInputDialog("Please enter the name of a file:");
letter = JOptionPane.showInputDialog("Please enter a letter contained in the string");
// Open the file for reading
File file = new File(fileName);
Scanner inputFile = new Scanner(file); // Declare new scanner object for file reading
// Set accumulator to zero
int count = 0;
if (inputFile.nextLine().equalsIgnoreCase(letter)) {
count++; // add letter occurrence
total += count; // add the letter occurrence to the total
}
BufferedReader reader = new BufferedReader(new FileReader("somefile.txt"));
int ch;
char charToSearch='a';
int counter=0;
while((ch=reader.read()) != -1) {
if(charToSearch == (char)ch) {
counter++;
}
};
reader.close();
System.out.println(counter);
这是什么帮助?
有错误你code.Correct代码如下─
String fileName; // Holds the name of the file
String letter; // Letter to search for in the file
// Get the name of the file and character from the user
fileName = "C:\\bin\\GWT.txt";
letter = "X";
// Open the file for reading
File file = new File(fileName);
Scanner inputFile = new Scanner(file); // Declare new scanner object for file reading
// Set accumulator to zero
int count = 0;
while(inputFile.hasNext()) {
if (inputFile.nextLine().toLowerCase().contains(letter.toLowercase())) {
count++; // add letter occurrence
}
}
System.out.println(count);
这个答案是假设在文本文件中每行只包含一个字母你的问题建议。
你需要用你的if语句在一个循环中你目前只检查文件的第一行:
while(inputFile.hasNext()) {
if (inputFile.nextLine().equalsIgnoreCase(letter)) {
count++; // add letter occurrence
total += count; // add the letter occurrence to the total
}
}
你也可以更换:
count++;
total+= count;
只
total++;
String line=""
while(inputFile.hasNext()) {
line = inputFile.nextLine();
for(int i=0; i<line.length(); i++ ){
if (line.charAt(i)== letter)
count++;
}
}