How to make a diamond using Nested For Loops

后端 未结 15 1136
终归单人心
终归单人心 2021-01-01 07:09

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 s         


        
15条回答
  •  说谎
    说谎 (楼主)
    2021-01-01 07:38

    Try this

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

提交回复
热议问题