J.b. Daniel J.b. Daniel - 1 month ago 11
Java Question

using java for loop with user input to make custom diamond

I am looking to make a diamond like this:

n=2

*
*$*
*


n=3

*
*$*
*$*$*
*$*
*


n=4

*
*$*
*$*$*
*$*$*$*
*$*$*
*$*
*


I can get the diamond with just
*
but cannot figure out how to add the
$
in the mix

My code is as follows:

import java.util.Scanner;

public class ForNestedDemo
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please input number of lines:");
int i = 0, j, k, n;
n = scan.nextInt();

for (k = 1; k <= (n + 1) / 2; k++) {
for (i = 0; i < n - k; i++) {
System.out.print(" ");
}
for (j = 0; j < k; j++) {
System.out.print("*$ ");
}
System.out.println("");
}

for (k = ((n + 1) / 2); k < n; k++) {
for (i = 1; i < k; i++) {
System.out.print(" ");
}
for (j = 0; j < n - k; j++) {
System.out.print(" *");
}
System.out.println("");
}

scan.close();
}
}

Answer

I agree that @GhostCat is the easiest way to go, but just for fun I figured it out using your way.

for (k = 1; k < (n + 1); k++) {
    for (i = 0; i < n - k; i++) {
        System.out.print(" ");
    }
    for (j = 0; j < k; j++) {
        if(j == 0)
            if(k == n+1)
                System.out.print("*");
            else
                System.out.print(" *");
        else{
            System.out.print("$*");
        }
    }
    System.out.println("");
}

for (k = 1; k < n; k++) {
    for (i = 0; i < k; i++) {
        System.out.print(" ");
    }
    for (j = 0; j < n - k; j++) {
        if(j == 0)
            if(k == n+1)
                System.out.print("*");
            else
                System.out.print(" *");
        else{
            System.out.print("$*");
        }
    }
    System.out.println("");
}

I have fixed some of your errors and added some checks in there also.

The logic I have in place is:

  1. If you are the first character, are you the middle row (k == n+1), if so, only print *, otherwise print _*.
  2. If you are not the first character, print $*.

After that I just simply took my logic and pasted it down below in your lower half loop.