Search code examples
javaloopswhile-loopsentinel

Ending process when negative height is entered


im having trouble finishing off this program, we are supposed to write a program to draw a triangle using "*", where it asks for the height and width, and we are required to have it go in a loop where it keeps asking for more heights and widths, until the user enters a negative value in the height, it is supposed to store there. Heres what i have so far.

import java.util.Scanner;

public class Rectangles {

public static void main(String[] args) {
    Scanner kbd = new Scanner(System.in);
    System.out.print("\n\n"
        + "Drawing Rectangles\n"
        + "------------------\n\n"); 
    while(height >= 0) {
        int height = -1, width = -1;
        System.out.print("Enter the height and width of a rectangle: ");
        height = kbd.nextInt();
        width = kbd.nextInt();
        kbd.nextLine();
        System.out.println("\n" 
            + "Here is your rectangle:");
        drawRectangle(height, width);
        System.out.print("\n\n");
    }
}

private static void drawRectangle(int height, int width) {

    for (int line = 1; line <= height; line++) {
        for (int star = 1; star <= width; star++) {
            System.out.print("*");
        }
        System.out.println();
    }
}

}

So far i have this, it starts, asks for height, width then draws a triangle thats it. any ideas how i could make it go in a loop to ask for more and stop only when the user enters a negative value in the height? NO IF STATEMENTS ALLOWED. Thanks in advance


Solution

  • public static void main(String[] args) {
    Scanner kbd = new Scanner(System.in);
    
    
    System.out.print("\n\n"
        + "Drawing Rectangles\n"
        + "------------------\n\n");
    
    int height = -1, width = -1;
    System.out.print("Enter the height and width of a rectangle: ");
    height = kbd.nextInt();
    width = kbd.nextInt();
    kbd.nextLine();
    while(height > -1) {
        System.out.println("\n" + "Here is your rectangle:");
        drawRectangle(height, width);
        System.out.print("\n\n");
    
        System.out.print("Enter the height and width of a rectangle: ");
        height = kbd.nextInt();
        width = kbd.nextInt();
        kbd.nextLine();
    }
    
    
    }
    
    private static void drawRectangle(int height, int width) {
    
    for (int line = 1; line <= height; line++) {
        for (int star = 1; star <= width; star++) {
            System.out.print("*");
    
        }
    
        System.out.println();
    }
    }