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
285 views
in Technique[技术] by (71.8m points)

java - How to make a diamond using nested for loops

So I was assigned to make a diamond with asterisks in Java and I'm really stumped. Here's what I've come up with so far:

public class Lab1 {
    public static void main(String[] args) {
        for (int i = 5; i > -5; i--) {
            for (int j = 0; j < i; j++) {
                System.out.print(" ");
            }
            for (int j = 0; j >= i; j--) {
                System.out.print(" ");
            }
            System.out.println("*");
        }
    }
}

output

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

In order to make a diamond you need to set spaces and stars in shape. I have made this simple program using only nested loops since I am a beginner.

public class Diamond {
    public static void main(String[] args) {
        int size = 9,odd = 1, nos = size/2; // nos =number of spaces
        for (int i = 1; i <= size; i++) { // for number of rows i.e n rows
            for (int k = nos; k >= 1; k--) { // for number of spaces i.e
                                                // 3,2,1,0,1,2,3 and so on
                System.out.print(" ");
            }
            for (int j = 1; j <= odd; j++) { // for number of columns i.e
                                                // 1,3,5,7,5,3,1
                System.out.print("*");
            }
            System.out.println();
            if (i < size/2+1) {
                odd += 2; // columns increasing till center row 
                nos -= 1; // spaces decreasing till center row 
            } else {
                odd -= 2; // columns decreasing
                nos += 1; // spaces increasing

            }
        }
    }
}

As you can see nos is the number of spaces. It needs to be decreased until the center row, and the number of stars needs to be increased but after the center row it's the opposite, i.e spaces increase and stars decrease.

size can be any number. I set it to 9 over here so I will have a size 9 star that is 9 rows and 9 columns max... number of space (nos) will be 9/2 = 4.5 . But java will take it as 4 because int can not store decimal numbers and the center row will be 9/2 + 1 = 5.5, which will result in 5 as int.

So first you will make rows... 9 rows hence

(int i=1;i<=size;i++) //size=9

then print spaces like I did

(int k =nos; k>=1; k--) //nos being size/2

then finally stars

(int j=1; j<= odd;j++)

once the line ends...

You can adjust stars and spaces using an if condition.


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

...