Diamond with nested for loop in Java

前端 未结 7 606
暗喜
暗喜 2021-01-23 13:27

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

Here is my code so far:

public          


        
7条回答
  •  隐瞒了意图╮
    2021-01-23 14:16

    Try this code. Using Math.abs will be a lot simple.

    import java.util.Scanner;
    
    public class MakeDiamond {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            while (true) {
                System.out.println("Let's Creat Diamonds");
                System.out.println("If number increases Diamonds gets bigger. " +
                        "Please input number lager than 1 : ");
    
                int user_input = sc.nextInt(); //gets user's input
                System.out.println("");
    
                int x = user_input;
                int front_space = -5;
                for (int i = 0; i < 2 * user_input + 1; i++) {
                    for (int a = front_space; a < Math.abs(i - user_input); a++) {
                        System.out.print("    ");
                    }
    
                    if (i < user_input + 1) {
                        for (int b = 0; b < 2 * i + 1; b++) {
                            System.out.print("*  ");
                        }
    
                    } else if (i > user_input) {
                        for (int c = 0; c < 2 * x - 1; c++) {
                            System.out.print("*  ");
                        }
                        x--;
                    }
                    System.out.print('\n');
                }
    
                System.out.println("\nRun Again? 1 = Run,  2 = Exit : ");
    
                int restart = sc.nextInt();
                System.out.println("");
                if (restart == 2) {
                    System.out.println("Exit the Program.");
                    System.exit(0);
                    sc.close();
                }
            }
        }
    }
    

提交回复
热议问题