实验预备
需要在桌面上用记事本建立一个名为“测试文档.txt”的文件,然后在其中进行输入几行单词,保存即可
源代码
import javax.swing.filechooser.FileSystemView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.Buffer;
import java.util.*;
public class ww3
{
public static void main(String[] args)
{
try
{
Scanner in=new Scanner(System.in);
File desktop = FileSystemView.getFileSystemView().getHomeDirectory();
String path = desktop.getAbsolutePath() + "\\测试文档.txt";
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String result="";
String s=null;
int line=1;
while((s=br.readLine())!=null)
{
result += '\n'+s;
line++;
}
String a;
System.out.println("请输入要查找的英文单词");
a=in.next();
FindCow(a,result);
}catch(Exception e){e.printStackTrace();}
}
public static void FindCow(String a,String Tofind)
{
int amount=0;
int count=1;
int line=0;
char b[] = Tofind.toCharArray();
for (int i = 0, k = 0; i < b.length; i++)
{
if(b[i]=='\n')
{
line++;
count=1;
}
while(b[i]==a.charAt(k)&&k<a.length())
{
if(b[i]=='\n')
{
line++;
count=1;
}
k++;
i++;
if (b[i] != a.charAt(k))
{
k = 0;
break;
}
if(k==a.length()-1)
{
System.out.println("该单词所在位置为第" + line + "行的第" + count + "个");
count=0;
k=0;
amount++;
continue;
}
}
if (b[i] == ' ')
count++;
}
System.out.println("单词一共出现了"+amount+"次");
}
}