Java - Hourglass

I am missing just a little bit. What I want:

*******
 *****
  ***
   *
  ***
 *****
*******

What i get

*******
 *****
  ***
   *
   *
  ***
 *****
*******

Code

public class HD404 {
    public static void main(String[] args) {

        int N = StdIn.readInt();
        int x = N*2-1;

        for (int i = 0; i < N; i++) {
            for (int j = i; j > 0; j--) {
                StdOut.print(" ");
            }
            for (int k = 0; k < x; k++) {
                StdOut.print("*");
            }
            x-=2;
            StdOut.println();
        }

        x = 1;
        for (int i = 0; i < N; i++) {
            for (int j = i; j < N-1; j++) {
                StdOut.print(" ");
            }
            for (int k = 0; k < x; k++) {
                StdOut.print("*");
            }
            x += 2;
            StdOut.println();
        }

    }
}

Now I'm just guessing, and I just can’t indicate my mistake. What am I missing here?

+4
source share
3 answers

The problems lie with the second part of your code, where you ask to draw one star, and you start from scratch, where you have to start from one.


Decision

x = 1;
for (int i = 0; i < N; i++)

should be replaced by

x = 3;
for (int i = 1; i < N; i++)
+1
source

The problem is that you start to draw the bottom of the hourglass with 1 asterisk ( x = 1) instead of 3.

, N-2, N-1, 1 0. , .

:

public static void main(String[] args) {

    int N = StdIn.readInt();
    int x = N*2-1;

    for (int i = 0; i < N; i++) {
        for (int j = i; j > 0; j--) {
            StdOut.print(" ");
        }
        for (int k = 0; k < x; k++) {
            StdOut.print("*");
        }
        x-=2;
        StdOut.println();
    }

    x = 3; // <-- not 1 here, the first line has 3 asterisks
    for (int i = 1; i < N; i++) { // <-- i starts at 1 because the first line was already drawn in the upper half
        for (int j = i; j < N-1; j++) {
            StdOut.print(" ");
        }
        for (int k = 0; k < x; k++) {
            StdOut.print("*");
        }
        x += 2;
        StdOut.println();
    }

}

, :

  • x , 0 x ( ) ,
  • x , , *.
  • * , min(i, x-i) max(i, x-i) ( , i < x-i , i > x-i).

:

public static void main(String[] args) {
    int N = 4;
    int x = 2 * N - 1;

    for (int i = 0; i <= x; i++) {
        if (i == N) continue; // skip the middle-line for it not to be drawn twice
        for (int j = 0; j < x; j++) {
            System.out.print(j >= Math.min(i, x-i) && j < Math.max(i, x-i) ? "*" : " ");
        }
        System.out.println();
    }
}

:

*******
 ***** 
  ***  
   *   
  ***  
 ***** 
*******
0

The easiest way I can come up with is probably to prevent the last iteration of your first outer loop, so you prevent the first single line from appearing.

I would do this:

for(int i = 0; i < N && x > 1; i++)
{
    /*Code of the first inner loop*/
}
0
source

Source: https://habr.com/ru/post/1618729/


All Articles