Java 文件状态和搜索行中某些单词时出现问题
FileStats类在显示有多少行包含用户请求的文本时遇到了一些问题。我不断得到错误的答案,有多少行包含文本。我相信我的代码忽略了标点符号(例如,它不会检测到)和大写的变化,如(the) 例如,如果一个文件包含5268行,其中1137行包含单词“the”,那么我的代码返回的输出表示它只包含1032行包含单词“the” 任何帮助都将不胜感激,谢谢。代码如下Java 文件状态和搜索行中某些单词时出现问题,java,Java,FileStats类在显示有多少行包含用户请求的文本时遇到了一些问题。我不断得到错误的答案,有多少行包含文本。我相信我的代码忽略了标点符号(例如,它不会检测到)和大写的变化,如(the) 例如,如果一个文件包含5268行,其中1137行包含单词“the”,那么我的代码返回的输出表示它只包含1032行包含单词“the” 任何帮助都将不胜感激,谢谢。代码如下 public static void main(String[] args) throws Exception { Scanner
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in); //creating object for scanner class
System.out.println("Enter a filename");
String file_name = input.nextLine(); //asking user to enter a file name
int word_line_count =0, line_count=0; //count variables for counting the line count and word occurance count
String search_word = input.nextLine(); //asking user to enter a search_Word
File f = new File(file_name); //Creating File Descriptor for reading input file
String[] words_sentence = null; //creating string which stores the all words in a line
FileReader file_object = new FileReader(file_name); // Creating File Reader object
BufferedReader buffer = new BufferedReader(file_object); //Creating BufferedReader object
String sentence;
while((sentence=buffer.readLine())!=null) //Reading Content from the file till the end of file
{
if (sentence.contains(search_word))
{
word_line_count++;
}
line_count++; //increment line count for every while loop iteration
}
System.out.println(file_name + " has " + line_count + " lines"); //printing the line count
System.out.println("Enter some text");
System.out.println( word_line_count+ " line(s) contain "+"\""+search_word+"\""); //printing the number of lines contains the given word
file_object.close(); //closing file object
}
}
“要求用户输入搜索词”您忘记实际要求用户,您知道,通过打印类似于
输入搜索词的内容。文件f
的意义是什么?您从未使用过它。”1137行中包含单词“the”,我的代码返回的输出表示它只包含1032行中包含单词“the”。您确定其他105行中不包含单词“the”?该方法区分大小写。如果希望和之间的比较相等,请调用。新代码是否区分大小写?抱歉,我上传了未更新的是,区分大小写。任何javadoc没有明确指出它不区分大小写的方法都是区分大小写的。