简体   繁体   English

打印星号-Java /文本文件

[英]Printing asterisks - java/text files

Sorry for the poorly worded question, I was in a hurry this morning because class was ending. 对于措辞不好的问题,很抱歉,今天早上我急忙上课,因为课程即将结束。

-- -

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

I need this to be the output: 我需要将其作为输出:

* * * * * 
* * * * 
* * * 
* * 
* 

So the height is the number of rows, which is 5. I could get this 因此,高度是行数,即5。

* 
* * 
* * * 
* * * * 
* * * * * 

with a similar code to above, but it didn't work for me. 与上面类似的代码,但对我不起作用。 I tried to get the inverse, but it didn't work. 我试图求逆,但是没有用。

Try this: 尝试这个:

    final int maxS = 10;

    for (int row = 1; row <= maxS; row ++) {
        for (int star=maxS; star >= row; star--) {
            System.out.print("* ");
        }
        System.out.println();
    }

With your actual code, you will get a square, here is an example on how you can achieve it: 使用您的实际代码,您将得到一个正方形,这是有关如何实现的示例:

I've replaced the first for by: 我已将第一个替换for

for (int row = maxS; row >= 1; row--)

and the second for by: 和第二for由:

for (int star = 1; star <= row; star++)

public static void main(String[] arv) throws Exception {
    final int maxS = height;
    for (int row = maxS; row >= 1; row--) {
        for (int star = 1; star <= row; star++) {
            System.out.print("* ");
        }
        System.out.println();
    }
}

Try: 尝试:

int maxS = height;
for (int row = 1; row <= maxS; row ++)
{
    for (int star = maxS - row + 1; star >= 1; star--)
    System.out.print("* ");
    System.out.println();
}

You have to think step by step. 你必须想一步一步来。 What happens at each outer loop, and each inner loop. 在每一个外循环,每个内环会发生什么。 It is very easy actually. 实际上,这很容易。 If you cannot get it working, you should manually go through each loop on paper. 如果无法正常工作,则应手动遍历纸上的每个循环。 You want it to decrease at each iteration, so you have to use -- instead of ++ . 您希望它在每次迭代时都减少,因此必须使用--而不是++

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM