在文本文件中搜索並計數單詞,但無法使用分隔符忽略句號。我使用分隔符來忽略單詞後面的句號。我試圖通過使用用戶輸入創建一個文件,然後詢問他們想要在文本文件中搜索的詞,並向他們顯示文本中發生的次數。 這是我的主類 公共類主要 {在文本文件中搜索並計數單詞,但無法忽略使用分隔符的句號
public static void main(String []args) throws IOException
{
str s=new str();
s.writer();
s.reader();
}
}
this is my class that has both the methods to create and read a file.
public void reader()
{
String s;
int i=0;
//Reading The File
try {
FileReader f=new FileReader("karan.txt");
Scanner sc=new Scanner(f);
Scanner st=new Scanner(System.in);
System.out.print("Enter string to be found and counted: ");
s=st.nextLine();
System.out.print("\n");
sc.useDelimiter(".");
sc.nextLine();
while(sc.hasNext())
{
if(sc.next().equals(s))
{
i++;
}
}
System.out.println("The number of times the word "+s+" is present is "+i);
} catch (FileNotFoundException ex) {
System.out.println("File not found");
}
}
//Writing The File
public void writer() throws IOException
{
try {
FileWriter fw=new FileWriter("karan.txt");
PrintWriter p=new PrintWriter(fw) ;
Scanner st=new Scanner(System.in);
System.out.println("Enter Text.");
p.print(st.nextLine());
p.close();
System.out.println("File has been written successfuly.");
} catch (FileNotFoundException ex) {
System.out.println("Error!");
}
}
這是當我遵守了定界符線
Enter Text.
karan is best of the best.
File has been written successfuly.
Enter string to be found and counted: best
The number of times the word best is present is 0
這是輸出,當我刪除定界符線 輸入文本輸出。
karan is best of the best
File has been written successfuly.
Enter string to be found and counted: best
The number of times the word best is present is 2
BUILD SUCCESSFUL (total time: 23 seconds)
,但我想要的答案爲2,即使我寫 卡蘭是極品中的極品。 在最後注意到句號,我希望編譯器忽略句號並給出答案2,也就是說它也應該在句尾以最好的句號計數單詞。
感謝您的幫助提前。
什麼有這個做的JavaScript? – Snowmonkey