Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

88
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda