Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda