Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
Left-align doesn't work as I want it to

I feel like this is a question with an easy answer, but I can't seem to figure it out for some reason.

for (int i = 0; i < width; i++){
        for (int j = 0; j < height; j++) {

            switch (c) {
            case 'i': 
                System.out.printf("[%d]", val);
                break;
            case 'b': 
                System.out.printf("[x]");
                break;
            case 'w': 
                System.out.printf("[ ]");
                break;
            default:
                System.out.printf("[%c]", type);
                break;
            }
            System.out.printf("%-2s", "");
        }
        System.out.println();
    }

This is the code. I have a matrix and I want to print it out like a table. However, this code doesn't do that in a neat way.

Switching out System.out.printf("%-2s", ""); forSystem.out.print("\t"); works but the spacing between the rows are too wide.

Any suggestions?

Thanks!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

A straightforward solution is to do a two-step formatting:

  1. First, in your switch block, you assign the formatted text to a string
  2. In your System.out.printf statement that creates the right column width, you use the formatted string from step 1 as the value.

So in your switch block:

formatted = String.format("[%d]", val);

And below:

System.out.printf("%-6s", formatted);

In your case, which is still quite simple, you can also incorporate the column width in your switch block:

System.out.printf("[%4d]", val); // 4 = 6 (column width) minus 2 for the brackets
// ...
System.out.printf("[x]   "); // add 3 spaces to the end
// etc.
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!