简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM