0

I want to code a program that displays a grid of numbers like this picture

Grid Example:

Grid Example

StringBuilder sb = new StringBuilder();

for (int row = 0; row < getNumberOfRows(); row++) {
    for (int column = 0; column < getNumberOfColumns(); column++) {
        if (numbers[row][column] < 10) {
            sb.append(" " + numbers[row][column] + " ");
        } else {
            sb.append(numbers[row][column] + " ");
        }
    }
    sb.deleteCharAt(sb.length()-1);
    sb.append("\n");
}

This is my current code however feel like using an if statement is not efficient and thought there might be an alternative way where the numbers are in placeholder positions.

1
  • There are other ways. For example, read the javadoc for String.format ... and the description of the formatter pattern language. HOWEVER ... the "efficiency" of if statements, and building strings like this is NOT what you should be considered here. Your real focus should be the readability of the code. (Even if there is a more performant way to write this code in Java, the overheads of assembling the output will be orders of magnitude less than the overheads of writing the characters on the screen via the user's console application.) Commented Nov 29, 2021 at 6:53

1 Answer 1

3

Use String.format():

sb.append(String.format(" %2d ", numbers[row][column]));

for all numbers. Meaning your code would look like:

for (int row = 0; row < getNumberOfRows(); row++) {
    for (int column = 0; column < getNumberOfColumns(); column++) {
        sb.append(String.format(" %2d ", numbers[row][column]));
    }
    sb.deleteCharAt(sb.length()-1);
    sb.append("\n");
}

The formatting conversion %d means "decimal integer" and %2d means the same, but with a minimum width of 2 chars (a space char being the default pad char, padding added by default to the left).


To go "next level", you could replace the inner loop with 1 statement:

sb.append(Arrays.stream(numbers[row])
  .mapToObj(i -> String.format("%2d", i))
  .collect(Collectors.joining(" ", "", "\n")));

which streams the entire row and handles the spacing, trimming and newline etc all in one operation.


I leave the final level, doing it all in one statement, as an exercise for the reader.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.