VeryJazzy
VeryJazzy

Reputation: 45

How to reset values in nested while loops?

Not sure if my title is relevant to the problem I have but im trying to print a rectangle using a method with 2 parameters (width and height) width works fine but I cant get height working.

I've commented out the nested while loop which I thought would solve the problem but once the width loop has completed once "i" still has max value of 17 from the original first loop. The exercises so far have been fairly simple so not sure if this is the rough way the problem was intended to be solved or if there is an easier way?

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    printrectangle(17,3);
    }


public static void printrectangle(int width, int height) {
    int i = 0;
    int p = 0;

    //while (p < height) {
        while (i < width) {
            System.out.println("*");
            i++;
            }
        //p++;
        //}



}   

}

Upvotes: 0

Views: 426

Answers (1)

elbraulio
elbraulio

Reputation: 994

this should work

while (p < height) {
    // print line with width i
    while (i < width) {
        // print without ln
        System.out.print("*");
        i++;
    }
    // completed a line, then reset i
    i = 0;
    // next line
    System.out.println();
    p++;
}

Upvotes: 1

Related Questions