tags:

views:

89

answers:

2

I'm trying to create a triangle where empty cells have spaces and non empty cells have X's.

public static char[][] Triangle(int size) {
    char[][] triangle = new char[size][size];

    for (int i = 0; i < size; i++) {
        Arrays.fill(triangle[i], '_');
    }

    for (int rows = 0; rows < size; rows++) {
        for (int columns = 0; columns < rows + 1; columns++) {
            triangle[rows][columns] = 'T';

        }
    }

    return triangle;
}

Somethings not working though. Not sure what it is? Edit: I found a fix and made the changes above.

A: 

You didn't specify the column size in declaration.

sza
It was initially I was just tweaking around with it..but that still doesnt solve the issue.
fprime
+1  A: 

You should add an if-clause within the 2nd loop. For example

if (rows == columns)

will put X on the main diagonal. I don't know what's your exact condition, but add it there.

(Also, use curly brackets, especially with nested constructs - it makes it more readable and less error-prone)

Bozho
I dont get how this will help? What does this if do?
fprime
currently you are putting `x` everywhere. Adding an if will limit the X-es to the positions you want.
Bozho
Ok I did that, but now that only puts an X where the rows and columns are equal. That should be the stopping point, but what about all the cells before? For example on the 3rd row, if there are five cells total, then I only have an X in the middle. What about the first 2 cells? How can I fix this?
fprime
Ok I tweaked around a bit and found the fix: for(int rows=0;rows<size;rows++){ for(int columns=0;columns<rows+1;columns++) { triangle[rows][columns]='T'; }I still dont understand how this loop works though. I run it on paper but I'm only getting diagonal output, not triangular.
fprime
@fprime - where in the question did you specify you want trianglular X-es? And Where do you suppose to have them - show what output you expect and don't make us assume.
Bozho