While Within While (While Main Stops)

-1

I need to create 2 loops going from 1 to 10, just one inside another.

WORKS

  • Using for and for.
  • Using while and for.

Why does not it work?

1) WHILE AND WHILE

int a=1, b=1;

    while(a<=10) {          
        while(b<=10) {
            System.out.print(a + "-" + b + "  ");
            b++;
        } //fim while b
        System.out.println("");
        a++;
    }//fim while a

2) FOR AND WHILE

int b=1;

    for(int a=1; a<=10; a++) {
        while(b<=10) {
            System.out.print(a + "-" + b + "  ");
            b++;                
        }// fim while b
    }// fim for a
    
asked by anonymous 27.03.2018 / 17:19

2 answers

3

Your while - > while is working. He is correct.

The problem is that the condition of the second while (b<=10) will always be false after the first loop , this is because you are adding 1 to variable b and is not resetting its value, for example:

public class HelloWorld
{
  public static void main(String[] args)
  {
    int a=1, b=1;

    while(a<=10) {          
        while(b<=10) {
            System.out.print(a + "-" + b + "  ");
            b++;
        }
        System.out.println("");
        a++;
        b = 1; //Reseta o valor de "B"
    }
  }
}
    
27.03.2018 / 17:26
2

Just to teach you the simplest and most logical way:

public class Contador {
    public static void main(String[] args) {
        int a = 1;
        while ( a < 11) {
            int b = 1;
            while (b < 11) System.out.printf("%02d - %02d, ", a, b++);
            System.out.println();
            a++;
        }
    }
}

See running on ideone . And no Coding Ground . Also I placed in GitHub for future reference .

    
27.03.2018 / 17:39