我们应该创建一个程序,从 JTextField 读取单词并将其与列表进行比较,然后我们必须计算该单词的行数(如果存在)并在同一行中显示另一个文本文件中的同一行程序到另一个 JTextField (它应该是某种字典)这是我所拥有的:
boton1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String palabra=tx1.getText();
boton3.setEnabled(true);
try{
// here is where i open my file
FileInputStream fstream = new FileInputStream("src/archivos/translator.txt");
DataInputStream entrada = new DataInputStream(fstream);
BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));
String strLinea;
while ((strLinea = buffer.readLine()) != null) {
System.out.println (strLinea);
int i=0;
while (!(strLinea.equals(palabra))){
i++;
}
tx2.setText(String.valueOf(i));
}
entrada.close();
}catch (IOException x){
System.err.println("Oh no, ocurrió un error: " + x.getMessage());
}
}} );
最佳答案
根据我对你所说的理解,首先,你应该改变:
while (!(strLinea.equals(palabra))){
至
while (!(strLinea.contains(palabra))){
您想要查看该行是否包含该单词,而不是该行与 TextArea
的内容相同。另外,您还需要向该 while 循环的内容添加另一个语句。目前,如果文档中没有出现该单词,它只会永远增加“i”。如果当前行没有,您希望它将 strLinea 移动到下一行,如果有,您将想要终止循环。
关于java - Java 比较单词与文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24112237/