开发者

Java Array Question

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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜