Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

java - Display an ASCII diamond with nested for loops

I am trying to display a diamond of asterisks using nested for loops.

Here is my code so far:

public class Diamond {
    public static void main(String[] args) {
        int size = 9;
        for (int i = 1; i <= size; i += 2) {
            for (int k = size; k >= i; k -= 2) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }// end loop

        for (int i = 1; i <= size; i += 2) {
            for (int k = 1; k <= i; k += 2) {
                System.out.print(" ");
            }
            for (int j = size; j >= i; j--) {
                System.out.print("*");
            }
            System.out.println();
        }// end loop
    }
}

This is close, but I'm printing the line of 9 asterisks twice.

How can I adjust the second for loop to start the output at 7 asterisks and 2 spaces?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your first for loop remove = mark and just use < e.g.

for (int i = 1; i < size; i += 2)

Full code:

int size = 9;

for (int i = 1; i < size; i += 2) {
    for (int k = size; k >= i; k -= 2) {
        System.out.print(" ");
    }
    for (int j = 1; j <= i; j++) {
        System.out.print("*");
    }
    System.out.println();
}// end loop

for (int i = 1; i <= size; i += 2) {
    for (int k = 1; k <= i; k += 2) {
        System.out.print(" ");
    }
    for (int j = size; j >= i; j--) {
        System.out.print("*");
    }
    System.out.println();
}// end loop

Output:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...