Luca Prestipino
Luca Prestipino

Reputation: 1

do while loop to draw a square

int alto; int ancho;

    System.out.println("Dame el alto: ");
    alto = scanner.nextInt();
    System.out.println("dame el ancho: ");
    ancho = scanner.nextInt();

    int impresosAlto;
    int impresosAncho;

    do {
        impresosAlto = 0;
        impresosAncho = 0;

        do {

            System.out.print("*");

            impresosAncho++;

        } while (impresosAncho != ancho);

        System.out.println();

        impresosAlto++;

    } while (impresosAlto != alto);

    //

}

}

do while loop issue Hi I´d like to sort this out but when i debug it , I have issues that the "impresosalto" stand whit int 1 instead of to , and the loop keep running in an infinite loop don´t know why , any help- advice ? thanks tried to change variables here and there but nothing worked out

Upvotes: 0

Views: 244

Answers (2)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

public static void main(String... args) throws IOException {
    Scanner scan = new Scanner(System.in);

    System.out.print("height: ");
    final int height = scan.nextInt();

    System.out.print("width: ");
    final int width = scan.nextInt();

    int row = 1;

    do {
        int col = 1;

        do {
            boolean star = row == 1 || row == height || col == 1 || col == width;
            System.out.println(star ? '*' : ' ');
        } while (++col <= width);

        System.out.println();
    } while (++row <= height);
}

Demo

height: 4
width: 6
******
*    *
*    *
******

Upvotes: -1

Snehil Agrahari
Snehil Agrahari

Reputation: 288

It is happening because your second condition of Alto is never reached, after every iteration impresosalto becomes zero. Put impresosalto=0 outside the loop and it will work fine 👍

ImpresosAlto=0 move up two lines

Upvotes: 3

Related Questions