How do I get the next loop to run?

Asked

Viewed 64 times

5

I have a list with two or more strings:

[Panel, Control]

Now comes the problem:

for (int i = 0; i < lista.size(); i++){
    String linha = "";
    while ((linha = leitura.readLine()) != null){
        if (linha.contaens(lista.get(i))){
            System.out.println(lista);

1 - Executes for with i equal to 0.

2 - Run while and read line by line looking for the first string in the list until you reach null.

3 - The for is called again with i equal to 1.

4 - while does not execute, because the leitura.readLine() flipped null.

5 - How do pro while run until lista.size() times? Until the list runs out.

In my code it only fetches the first String from the list, but the next one does not execute because the line turned null in the first search.

  • don’t understand your problem. Your problem is that you have a line like this? "A B" and you want to catch A first, then B?

  • No. When the while runs for the first time, it is true, now when it runs for the second time, it is false... like letting it true?

1 answer

4


D3ll4ry,

would like to understand why you would like to read the same line 2 times to post an answer that best suits your situation.

But if you really believe that the best way would be to read the same line 2 times, you have to close the file and open it every iteration of for.

for (int i = 0; i < lista.size(); i++){
    /* Abre o arquivo, continue utilizando o que você está usando
       para abrir o arquivo, só coloquei o BufferedReader de exemplo */
    BufferedReader leitura = new BufferedReader(new FileReader('arquivo.txt');
    String linha = "";
    while ((linha = leitura.readLine()) != null){
        if (linha.contaens(lista.get(i))){
            System.out.println(lista);
        }
    }
    leitura.close(); // Fecha o arquivo
}

This happens because you open your file before the for, reads all the lines in your while, but when you come back on for, your file has been completely read.

  • It is because each reading is a different search. Solved my problem, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.