java 用Java打印一个星号矩形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33487201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:44:57  来源:igfitidea点击:

Printing a rectangle of asterisks in Java

javaloopsfor-loopasterisk

提问by 011012

The following is the source code to print a rectangle entirely composed of asterisks (*), with a test class included as well.

以下是打印完全由星号 (*) 组成的矩形的源代码,还包括一个测试类。

import javax.swing.JOptionPane ;

/**
 * A class to print block rectangles.
 */
class RectanglePrinter
{
    // instance var's
    int height ;            // height of rectangle (i.e. number of segments)    
    int width ;             // width of each segment(i.e. number of "*"s printed) 

    /**
     * Create a RectanglePrinter object.
     * @param height height of rectangle (i.e., number of lines to print)
     * @param width width of rectangle (i.e., number of '*'s per line
     */
    public RectanglePrinter(int height, int width)  // constructor
    {
        this.height = height ;
        this.width = width ;
    }

    /**
     * Prints one line of a rectangle, by printing exactly "width" asterisks
     */ 
    public void printSegment()
    {
        // write the body of this method here


    }

    /**
     * Prints a rectangle exactly "height" lines in height.  Each line is 
     * printed via a call to method printSegment
     */ 
    public void printRectangle()
    {
        System.out.println("Printing a " + height + " x " + width + " rectangle:") ;
        // write the body of this method here


    }

}  // end of class rectanglePrinter definition

public class RectanglePrinterTest
{
    public static void main (String [] args)
    {
        String input = JOptionPane.showInputDialog
                                   ("What is the height of the rectangle?") ;
        int height = Integer.parseInt(input) ;

        input = JOptionPane.showInputDialog
                            ("What is the width of the rectangle?") ;

        int width = Integer.parseInt(input) ;

        RectanglePrinter r = new RectanglePrinter(height, width) ;

        System.out.println() ;
        r.printRectangle() ;
        System.out.println() ;
    }
}

In the segments where it says to fill out the method body, I was instructed to use for loops to print out the asterisks. I think I have a basic idea of how to do the printSegment() method:

在它说要填写方法主体的部分中,我被指示使用 for 循环来打印星号。我想我对如何执行 printSegment() 方法有一个基本的想法:

for (int w = 1; w <= width; w++)
            {
                System.out.println("*");
            }

But from there, I am unsure of what to do within the printRectangle method. Judging from the comments in the code, I think I'm supposed to write a for loop in the printRectangle method that calls the printSegment method, except I don't think you can call a void method within the body of another method. Any help on this would be greatly appreciated.

但是从那里开始,我不确定在 printRectangle 方法中要做什么。从代码中的注释来看,我认为我应该在调用printSegment方法的printRectangle方法中编写一个for循环,除非我认为您不能在另一个方法的主体内调用void方法。对此的任何帮助将不胜感激。

Update:

更新:

I attempted to use the following code within the body of printRectangle()

我试图在 printRectangle() 的主体中使用以下代码

for (int h = 1; h <= height; h++)
                {
                    printSegment();
                }

After running the code and inputting the height and width, I received the following output:

运行代码并输入高度和宽度后,我收到以下输出:

Printing a 6 x 7 rectangle:
*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

Now I can print out the asterisks at least, so I just need to know how to modify the code so the output is a rectangular block of asterisks.

现在我至少可以打印出星号,所以我只需要知道如何修改代码,以便输出是一个矩形的星号块。

Update #2.

更新#2。

I figured out the solution. Here's the code that got me the result I was looking for.

我想出了解决办法。这是让我得到我正在寻找的结果的代码。

import javax.swing.JOptionPane ;

/**
 * A class to print block rectangles.
 */
class RectanglePrinter
{
    // instance var's
    int height ;            // height of rectangle (i.e. number of segments)    
    int width ;             // width of each segment(i.e. number of "*"s printed) 

    /**
     * Create a RectanglePrinter object.
     * @param height height of rectangle (i.e., number of lines to print)
     * @param width width of rectangle (i.e., number of '*'s per line
     */
    public RectanglePrinter(int height, int width)  // constructor
    {
        this.height = height ;
        this.width = width ;
    }

    /**
     * Prints one line of a rectangle, by printing exactly "width" asterisks
     */ 
    public void printSegment()
    {
        // write the body of this method here
                for (int w = 1; w <= width; w++)
                {
                    for (int h = 1; h <= height; h++)
                    {
                        System.out.print("*");
                    }
                    System.out.println();
                }


    }

    /**
     * Prints a rectangle exactly "height" lines in height.  Each line is 
     * printed via a call to method printSegment
     */ 
    public void printRectangle()
    {
        System.out.println("Printing a " + height + " x " + width + " rectangle:") ;
        // write the body of this method here
                printSegment();


    }

}  // end of class rectanglePrinter definition

public class RectanglePrinterTest
{
    public static void main (String [] args)
    {
        String input = JOptionPane.showInputDialog
                                   ("What is the height of the rectangle?") ;
        int height = Integer.parseInt(input) ;

        input = JOptionPane.showInputDialog
                            ("What is the width of the rectangle?") ;

        int width = Integer.parseInt(input) ;

        RectanglePrinter r = new RectanglePrinter(height, width) ;

        System.out.println() ;
        r.printRectangle() ;
        System.out.println() ;
    }
}

The differences made: I added a nested for loop in the body of the printSegment() method, and instead of using System.out.println("*");, used System.out.print("*")in the innermost loop, and System.out.println()in the outer loop, which resulted in the following output for the input of 5 x 7:

产生的差异:我在 printSegment() 方法的主体中添加了一个嵌套的 for 循环,而不是 using System.out.println("*");System.out.print("*")在最内层循环和System.out.println()外层循环中使用,这导致以下输出用于 5 x 7 的输入:

Printing a 5 x 7 rectangle:
*****
*****
*****
*****
*****
*****
*****

回答by Markus Maga

It does indeed sound like you are supposed to make a loop in printRectanglewhere you call printSegmentfor height amount times.

这确实听起来像你应该printRectangle在你调用printSegment高度量时间的地方做一个循环。

To call your printSegmentmethod inside printRectanglesimply write printSegment();to call it.

printSegment在内部调用您的方法,printRectangle只需编写printSegment();调用它即可。

Since its in the same class this is all you have to do to call it. If it were called from another class you can check how RectanglePrinterTestmain method calls printRectangleusing r.printRectangle();where ris an instance of the RectanglePrinterclass.

由于它在同一个类中,这就是您调用它所需要做的全部工作。如果它是从另一个类调用的,您可以使用where是类的实例来检查RectanglePrinterTestmain 方法的调用方式。printRectangler.printRectangle();rRectanglePrinter

As its a void method it wont return anything so you don't need to do anything else. :)

由于它是一个 void 方法,它不会返回任何内容,因此您无需执行任何其他操作。:)

So to sum it up you are on the right track! Keep going and just try what you think feels right and you will surely figure it out.

所以总而言之,你走在正确的轨道上!继续前进并尝试您认为正确的方法,您一定会弄清楚的。

回答by 10 Replies

You need to use the "\n" string to print a new line. It should print the "\n" every time the width or row command is completed.

您需要使用“\n”字符串来打印新行。每次完成宽度或行命令时,它应该打印“\n”。

回答by JJS

Using pieces of your code I can now successfully print a rectangle, horizontally.

使用您的代码片段,我现在可以成功地水平打印一个矩形。

The Helsinki CS MOOC (http://mooc.cs.helsinki.fi/) presented this task in its learn Java course.

赫尔辛基 CS MOOC ( http://mooc.cs.helsinki.fi/) 在其学习 Java 课程中介绍了此任务。

public class MoreStars {

    public static void main(String[] args) {    
        printRectangle(10, 6);
    }

    public static void printRectangle(int width, int height) {
        int i;
        int j;
        for ( i = 0; i < height; i++ ) {
            for ( j = 0; j < width; j++) {
                printStars(width);
            }
            System.out.println("");
        }                
    }

    public static void printStars(int amount) {   
        System.out.print(" * ");
    }
}