我正在为学校创建一个名为“Book”的程序,但遇到了很多麻烦。 IM 支持找出字符“a”在 txt 文件中出现的次数。 txt 文件内容如下“去洗手间 他说 他是对的 我需要去洗手间”。这是我的代码,但它似乎根本不起作用,我被卡住了。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Book
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner text = new Scanner (new File("data.txt"));
String word = null;
int count = 0;
while(text.hasNextLine())
{
word = text.nextLine();
for (int i = 0; i < word.length(); i++)
{
if (word.substring(i) == "a")
{
count++;
}
}
}
System.out.print(count);
}
}
最佳答案
带有一个参数的子字符串
返回一个从给定索引开始的子字符串。另外,在 Java 中通常不会使用 ==
来比较字符串。
您需要将 a
用单引号括起来以使其成为字符常量,并且 charAt
获取字符串的特定字符,如下所示:
if (word.charAt(i) == 'a')
关于java - 如何查找txt文件中某个字母出现了多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20895658/