简体   繁体   中英

Compare word to Text file Java

we are supposed to create a program that reads a word from a JTextField and compare it to a list, then we have to count how many lines to the word if it exist and display the same line from another text file in the same program into another JTextField (it's supposed to be a Dictionary of some sort) here is what i have:

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());
    }

}} );

Based on my understanding of what you said, first, you should change:

while (!(strLinea.equals(palabra))){

to

while (!(strLinea.contains(palabra))){

You want to see if the line contains that word, not that the line is the same as the contents of the TextArea . Also, you'll want to add another statement to the contents of that while loop. Currently it'll just increment "i" forever if the word doesn't come up in the document. You want it to move strLinea to the next line if the current one doesn't have it, and if it does, you'll then want to terminate the loop.

I think your problem is

while ((strLinea = buffer.readLine()) != null)   {
          System.out.println (strLinea);
    int i=0;
    while (!(strLinea.equals(palabra))){
    i++;

    }
tx2.setText(String.valueOf(i));
    }

In inner while loop, you are iterating forever. If you want to compare each word in the file to the JTextField value, you should write

int i = 0;   
while ((strLinea = buffer.readLine()) != null)   {
    i++;
    System.out.println (i + " " + strLinea);
    if (strLinea.equals(palabra)){
        tx2.setText(String.valueOf(i));
        break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM