user8737641
user8737641

Reputation:

Java : nested loops

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.

Upvotes: 0

Views: 2676

Answers (3)

maxy
maxy

Reputation: 5

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.

Upvotes: 0

Oleg
Oleg

Reputation: 6324

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();
}       

Upvotes: 1

Ringuerel
Ringuerel

Reputation: 122

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

Upvotes: 0

Related Questions