在Java中使用BufferedReader类读取文本文件
我正在尝试创建一个名为在Java中使用BufferedReader类读取文本文件,java,substring,bufferedreader,Java,Substring,Bufferedreader,我正在尝试创建一个名为findOccurrences()的静态方法,它接受一个名为subString的字符串参数。首先,该方法必须提示用户输入扩展名为.txt的文件的路径名,然后使用该文件创建文件对象。然后,该方法需要在该文件上打开一个流。随后,该方法必须一次从流中读取一行,并且对于每一行,该方法需要将该行中字符串参数子字符串的出现次数打印到标准输出 该方法的示例输出如下所示: The substring "FRED" occurs 2 times in line 1 The substring
findOccurrences()
的静态方法,它接受一个名为subString
的字符串
参数。首先,该方法必须提示用户输入扩展名为.txt
的文件的路径名,然后使用该文件创建文件
对象。然后,该方法需要在该文件上打开一个流。随后,该方法必须一次从流中读取一行,并且对于每一行,该方法需要将该行中字符串参数子字符串的出现次数打印到标准输出
该方法的示例输出如下所示:
The substring "FRED" occurs 2 times in line 1
The substring "FRED" occurs 1 times in line 2
The substring "FRED" occurs 4 times in line 3
The substring "FRED" occurs 0 times in line 4
该方法需要确保当while
循环终止时,文件中的所有行都已读取。保存文件当前行的字符串应转换为大写。在另一个循环中,该方法需要确定其参数(转换为大写)作为当前行中的子字符串出现的次数。因此,例如,如果当前行包含字符串“British Owning TALENT”,则搜索子字符串“SSES”时应出现两次
现在,我尽了最大努力,为所需的方法开发了下面的代码。但不幸的是,每次我编译它时,编译器都会抛出一个错误:foreach不适用于表达式类型
,这就是我被卡住的地方!所以我只是想知道你们是否能帮我找出哪里出了问题
下面是我开发的全部代码:
public static void countOccurrences (String subString)
{
OUDialog.alert("Please choose a file to search");
String pathname = OUFileChooser.getFilename();
File aFile = new File(pathname);
BufferedReader bufferedFileReader = null;
int numOfOccurrencesInLine;
int lineNumber = 0;
int lineIndex;
subString = subString.toUpperCase();
String currentLine;
try
{
bufferedFileReader = new BufferedReader(new FileReader(aFile));
currentLine = bufferedFileReader.readLine();
while (currentLine != null)
{
currentLine = bufferedFileReader.readLine();
currentLine.toUpperCase();
lineIndex = currentLine.indexOf(subString, lineNumber);
subString = currentLine.substring(lineIndex);
numOfOccurrencesInLine = 0;
for (int eachOccurrence : currentLine)
{
numOfOccurrencesInLine = numOfOccurrencesInLine + eachOccurrence;
System.out.println("The substring " + subString + "occurs 2 times in line " + lineNumber);
}
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedFileReader.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
谢谢你们 除了您确实应该将这些功能拆分为单个方法之外,您使用的foreach
是错误的。您正在迭代一个String[]
数组,因此需要将“int eachOccurrence”更改为String eachOccurrence
编辑:您实际上并没有遍历数组。您希望遍历字符串
,但字符串
未实现Iterable
你真的应该买一本像样的编程书。再次仔细阅读代码后,出现了几个错误。例如,你读了两行,覆盖了第一行。因此,只需保留第二个currentLine=bufferedFileReader.readLine()
(在null
检查之后的一个)。就个人而言,我认为对于单个方法来说,这太多功能了。但currentLine是一个字符串;此时您真正想做什么?currentLine是一个字符串,而不是intRead的最后一部分的iterable。你读台词的方式也是错误的。阅读String.indexOf()的javadoc:将行号作为参数传递是没有意义的。谢谢你们,我感谢你们的评论,我会继续努力的。