Repetition structure

3

I'm studying repetition structure in Java here. And I came across the urge to do the following:

public class Teste {

    public static void main(String[] args) throws IOException {

        for (int i = 1; i <= 2; i++) {
            for (int j = 1; j <= 2; j++) {
                System.out.println("Linha: " + j);
            }
            System.out.println(" Registro: " + i);
        }

    }
}

The output of this section is:

Linha: 1
Linha: 2
    Registro: 1
Linha: 1
Linha: 2
   Registro: 2

And the desired output would be:

Linha: 1
Linha: 2
    Registro: 1
Linha: 3
Linha: 4
   Registro: 2

That is, in the second spin of the first loop, j was not zeroed, thus generating Line 3 and Line 4 for the second register.

How do I do this?

    
asked by anonymous 04.03.2017 / 19:22

1 answer

1

You can do this:

for (int i = 1; i <= 4; i++) {

    System.out.println("Linha: " + i);

    if(i%2==0){
        System.out.println(" Registro: " + (i/2));  
    }
}

See working at ideone: link

Or to have control of the registration number and lines independently, just do the following:

int linhas = 3, 
registros = 2, 
temp = 1;

for (int i = 1; i <= registros; i++) {

    for(int j = 0; j < linhas; j++){
        System.out.println("Linha: " + (temp++));
    }
        System.out.println(" Registro: " + i);
}

The result of this example will be:

Linha: 1
Linha: 2
Linha: 3
 Registro: 1
Linha: 4
Linha: 5
Linha: 6
 Registro: 2

See this example working on ideone: link

    
04.03.2017 / 19:40