输入负高度时的结束过程

时间:2019-01-14 00:02:22

标签: java loops while-loop sentinel

如果无法顺利完成该程序,我们应该编写一个程序来使用“ *”绘制一个三角形,并在其中询问高度和宽度,并要求我们将其循环放置要求提供更多的高度和宽度,直到用户在高度中输入负值,它才应该存储在此处。这是我到目前为止所拥有的。

import java.util.Scanner;

公共类矩形{

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();
    }
}

}

到目前为止,我已经知道了,它开始,要求高度,宽度,然后画一个三角形。任何想法,我怎么可以让它循环请求更多并仅在用户输入高度的负值时停止?如果允许声明,则不行。预先感谢

1 个答案:

答案 0 :(得分:-1)

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();
}
}