miwa_p
miwa_p

Reputation: 435

drawing Diamond of numbers with 2D array in java

So I need to make a diamond_look of numbers using 2D array in Java. I got my results but with null before the diamond. For drawNumDiamond(9) I have to get a diamond look that goes until 5 and back. I know I can make it without using array, but I want to learn more about 2D arrays :this is how it should look like and what are my results

public class Example1{
  	private static void drawNumDiamond(int h) {

        if(h%2 != 0) {
            int size = h/2 +1;
            int count = 1;
            int loop = 1;
            String[][] dijamant = new String[h][];
            for(int row = 0; row < dijamant.length; row++) {

                dijamant[row] = new String[row+1];

                for(int kolona=0; kolona<=row; kolona++) {

                    dijamant[0][0] = "1";

                    for(int i=0; i< loop;i++) {

                        dijamant[row][kolona]+= count;

                    }

                }
                count++;
                loop+=2;

            }

            for (int k = 0; k < size; k++) {
                System.out.printf("%" + h + "s", dijamant[k]);
                h++;
                System.out.println();
            }
            h--;
            for (int q = size - 2; q>=0; q--) {
                h--;
                System.out.printf("%" + h + "s", dijamant[q]);
                System.out.println();
            }

        }
    }
    public static void main(String[] args) {

            drawNumDiamond(9);

    }
  }

Upvotes: 2

Views: 1101

Answers (1)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22224

The issue is in this line :

dijamant[row][kolona] += count;

if dijamant[row][kolona] is null and count is 2, the result of the string concatenation will be "null2". Try adding the following if statement before to initialize with an empty string :

if (dijamant[row][kolona] == null) {
    dijamant[row][kolona] = "";
}

This will get your code working, but there are still things to think about. E.g. you keep setting dijamant[0][0] = "1"; in the loop.

Upvotes: 1

Related Questions