我必须用java编写一个程序来读取一个文件,在每行中搜索单词"haystack"和"needle",如果单词"haystack"在单词"needle"之前有2行,则吐出单词"needle"的位置。到目前为止,我的程序将读取文件,如果它们在行中,则会吐出 2 个单词的位置,但如果"haystack"是 2 行之前,我不知道如何让它吐出"针"的位置。此外,如果其中一个单词不在行中,它会吐出 -1 作为位置。谁能帮忙?(请记住,我是一个初学者程序员,不是很擅长)。
这是我的代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.text.html.HTMLDocument.Iterator;
public class NeedleInHaystack{
public static void main(String[] args){
JFileChooser jfc = new JFileChooser();
int action = jfc.showOpenDialog(null);
if (action != JFileChooser.APPROVE_OPTION){
System.out.println("Ok, if you don't want to play");;
System.exit(3);
}
String fs = jfc.getSelectedFile().getAbsolutePath();
System.out.println("User selected: " + fs);
String fo = fs + "output.txt";
System.out.println("output: " + fo);
try {
FileReader fr = new FileReader(fs);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(fo);
PrintWriter pw = new PrintWriter(fw);
while (true) {
String l = br.readLine();
if (l == null) {
System.out.println("Looks like we are at the end of the line");
break;}
System.out.println("Input: " + l);
int firstNeedle;
int firstHaystack;
firstNeedle = l.indexOf("needle");
System.out.println("Found needle at:" + firstNeedle);
firstHaystack = l.lastIndexOf("haystack");
//String name = l.substring(0, firstNeedle);
System.out.println("found haystack at: " + firstHaystack);
//pw.println(l);
}
br.close();
pw.close();
System.out.println("That's all, folks!");
}catch(Exception e){
e.printStackTrace();
}
}
你需要一个在while循环中递增的counter
和一个在循环外声明的整数变量,它将存储找到"haystack"的行号。
,您将拥有"haystack"的行号,您可以将该行号与counter
进行比较。