If I wanna search for a word like "and" for example and my text file is
Saturday and Sunday
Hand
我的程序会将单词手数作为匹配,因为它包含单词和。我不知道如何修复它,尤其是因为搜索词被声明为用户输入。搜索文本文件中的特定单词 - 程序将单词片段计数为匹配
If I wanna search for a word like "and" for example and my text file is
Saturday and Sunday
Hand
我的程序会将单词手数作为匹配,因为它包含单词和。我不知道如何修复它,尤其是因为搜索词被声明为用户输入。搜索文本文件中的特定单词 - 程序将单词片段计数为匹配
假设您的搜索字母永远不会是每个句子的第一个单词。最简单的解决方案是在您的单词之前添加一个额外的空格。
喜欢的东西searchW=" "+searchW
后面还有一个空格,但假设这个单词不是最后一个单词(例如,方便) – Kelm
没有与你的代码的另一个问题 - 如果你在一行中有多个匹配,将只有一次算什么。这两者的原因是您搜索文件的方式 - 您检查每行是否包含字符串。如果你想的话的精确匹配,简单的方法来做到这一点是令牌化,像这样的行:
String[] tokens = text.split("\\s+");
现在你有一个字符串数组,每个那些是在当前正在行一个字处理。接下来,您可以使用equalsIgnoreCase()
做一个简单的比较(奖金 - 即使在单词大写的情况下也可以使用)。
你当然可以修改传递给拆分函数的定界符以包含标点符号,如果这是你需要的更多。
public class Test
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
File file=null;
boolean inputFile=false;
do
{
System.out.print("Enter a filename:");
String fileName = scan.nextLine();
inputFile= new File(fileName).isFile();
if(inputFile){
file=new File(fileName);
inputFile=true;
}
}while(!inputFile);
Scanner scanned = new Scanner(System.in);
System.out.println("Enter a word to search for: ");
String searchW = scanned.next();
int count = 0;
Scanner in = new Scanner(file);
String text=null;
while(in.hasNextLine())
{
text=in.nextLine();
if(text.contains(searchW))
{
count++;
System.out.println(text);
}
}
System.out.println("The word" + " " + searchW + " " + "was found" + " " + count + " " + "time(s) in this file");
scan.close();
in.close();
scanned.close();
}
}
建议: 1.不要使用file.exists()来检查文件。它主要检查目录。如果文件路径无效,它将会出现异常。 2.使用do while从用户获取有效路径。
为什么要删除您的程序。这是对以前的程序的修改。 –
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the filename: ");
String filename = scan.nextLine();
System.out.println("Please enter a word: ");
String wordname = scan.nextLine();
int count = 0;
try (LineNumberReader r = new LineNumberReader(new FileReader(filename))) {
String line;
while ((line = r.readLine()) != null) {
for (String element : line.split(" ")) {
if (element.equalsIgnoreCase(wordname)) {
count++;
System.out.println("Word found at line " + r.getLineNumber());
}
}
}
}
System.out.println("The word " + wordname + " appears " + count + " times.");
}
Javascript question tag removed - 这个问题与javascript无关。 –