java – How do I get the next loop to run?

Question:

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 – Execute while and read line by line looking for the first string in the list until reaching null .

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

4 – The while does not execute, because the leitura.readLine() becomes null .

5 – How do I make the while run up to lista.size() times? Until the list runs out.

In my code it only fetch the first String from the list, but the next one doesn't execute because the line became null in the first fetch.

Answer:

D3ll4ry,

I would like to understand why you would want 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 is because you open your file before the for , read all the lines in your while , but when you go back to the for , your file has already been completely read.

Scroll to Top