0

I'm very new in Java Programming Language.

I asked to make something like this with nested loops method:

picture1.

"Masukan Angka" is "Input Number" in Indonesian Language. So if we input 9, it will print out 9 lines of * and the amount of * decreased for each line.

I tried it with nested loops, this is what i made :picture2

The code is :

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Input your number: ");
        int x = in.nextInt();
        for (int y = x; y > 0; y--) {
            for (int z = 0; z < y; z++)
                System.out.print("*");
            System.out.println();
        }
    }

How can i make it doesn't filled up with * in the line 2-7, but instead filled with blank space like the example in the first picture?

Thanks in advance.

2
  • 2
    You could add an if( z == 0 || z == y-1 ) condition and then print Commented Oct 7, 2017 at 16:22
  • Welcome to Stack Overflow. Divide the problem into parts. The top is drawn different from the middle, and maybe the bottom Commented Oct 7, 2017 at 16:23

3 Answers 3

1

Expanding a bit on @Ringuerel solution:

for (int y = x; y > 0; y--) {
    for (int z = 0; z < y; z++) {
        // If it's first or last or first row print "*"
        if( z == 0 || z == y-1 || y == x) {
            System.out.print("*");
        }
        else {
            // Otherwise print " "
            System.out.print(" ");
        }
    }
    System.out.println();
}       
Sign up to request clarification or add additional context in comments.

Comments

0

Add this after the second for, before the print statement, if( z == 0 || z == y-1 ), sorry I'm using my phone

Comments

0
public static void main(String[] args) {
    int amount = 10;
    String c = "*";
    String message = "";
    for (int i = 0; i < amount; i++) {
        message += "*";
        for (int j = 1; j < amount - i; j++) {
            message += c;
        }
        message += "*";
        c = " ";
        System.out.println(message);
        message = "";
    }
    System.out.println("*");

}

You can try this if you want. Haven't tested it but I'm fairly certain it will work.

1 Comment

Adding to this, you the input you get. The amount will be the input -1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.