首页 > 解决方案 > 矩形打印机程序

问题描述

  1. 提示用户输入将显示为星号 (*) 字符的行和列的矩形的高度和宽度。

  2. 使用您对循环的了解,生成矩形输出。高度将是行数,宽度将是每行中的字符数。由于您的输出将一次生成一行,因此请确保在继续下一行之前完成每一行。

  3. 修改你的程序,使它只生成一个矩形的外边框,而不是一个填充的矩形。

我不知道如何让星号按行和列排列。

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {

        int width;
        int height;     

        Scanner input = new Scanner(System.in); 

        System.out.print("Enter the width:");
        width = input.nextInt();
        System.out.print("Enter the height:");
        height = input.nextInt();
        int y = 0;
        for (int x = 0; x <= width; x++){
            System.out.println("*");
            while (y <= height){
                y++;
                System.out.println("*");
            }
        }
    }
}

我试图得到一个看起来像这样的输出宽度 = 4 高度 = 4

****    ****
****    *  *
****    *  *
**** or ****

标签: java

解决方案


一些提示可以帮助您解决这个问题:

  1. println() always prints a newline character after the value you pass in. You probably only want that at the end of each line, not after each character.

  2. You don't need a while loop - you can do all of this work using two for loops.

  3. Break down what you need to achieve into smaller chunks and solve each chunk separately.

For example, a solid square (written as an algorithm, not as code):

loop y once for each row {

    loop x once for each column in that row {

        print a '*' character

    }

    print a newline character (because we have finished the row)

}

For example, a hollow square (written as an algorithm, not as code):

loop y once for each row {

    loop x once for each column in that row {

        if the current position is in the first row, last row, first column or last column
            print a '*' character
        otherwise
            print a ' ' character
    }

    print a newline character (because we have finished the row)

}

推荐阅读