java – Why doesn't one for within another work?

Question:

I have to deliver some console programs for tomorrow, but one is failing me. There is no error, it just doesn't do what I expect.

I need this loop to repeat another loop 18 times, but it only does it once and that's it.

Thank you in advance for your help.

package ejercicios_ciclos;
import javax.swing.*;
import java.util.*;
public class inscripcion {

    public static void main(String[] args)
    {
        System.out.println("´´´´´´´´´´´´´´´´´´´´´´´´");
        System.out.println("SISTEMA DE INSCRIPCIONES");
        System.out.println("------------------------");
        System.out.println("~~~~~~~~CBTis #59~~~~~~~");
        System.out.println("________________________");
        System.out.println("________________________");
        System.out.println("");

        int nau, nal, i, n=1;

        String nombre, esc, prom;

        for(i=1;i<19;i++){
            System.out.println("AULA NUMERO " + i);
            for(nal=n;n<51;n++){
                System.out.println("");
                System.out.println("'''''''''''''''''''''''''''''''''''''''''''''");
                nombre = JOptionPane.showInputDialog("Nombre:");
                esc = JOptionPane.showInputDialog("Escuela de procedencia:");
                prom = JOptionPane.showInputDialog("Promedio:");

                System.out.println("PROMEDIO DE SECUNDARIA: " + prom);
                System.out.println("");
                System.out.println("NOMBRE DEL ALUMNO: " + nombre);
                System.out.println("");
                System.out.println("ESCUELA ANTERIOR: "+ esc);
                System.out.println("");
                System.out.println("NÚMERO DE CONTROL = 0" + n);
                System.out.println("______________________________________________");

                System.out.println("PROMEDIO DE SECUNDARIA: " + prom);
                System.out.println("");
                System.out.println("NOMBRE DEL ALUMNO: " + nombre);
                System.out.println("");
                System.out.println("ESCUELA ANTERIOR: "+ esc);
                System.out.println("");
                System.out.println("NÚMERO DE CONTROL = 0" + n);
                System.out.println("______________________________________________");
            }
        }
    }
}

Answer:

Facts

  • n is defined outside of the first for .
  • the inner for does not reset the value of n for each cycle of the outer form.

Conclusion:

After completing the first loop, it no longer enters the inner for since n >= 51 .

Solution: where it says…

for(nal=n;n<51;n++){

Change for…

for(n=1;n<51;n++){

The value of n will return to 1 for each outer loop, thus re-entering the inner loop.

However, a better practice would be to define the variable inside the for

for(int n=1; n < 51; n++) {

(you should delete the old definition)

Scroll to Top