简体   繁体   中英

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

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

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 (int row = maxS; row >= 1; row--)

and the second for by:

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 ++ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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