java – Print array from left to right

Question:

The requirement is that it must be in a char array of 10 positions, at least this must be fulfilled.

I know that it can be done with 2 for, one to print and another to go picking up the positions and inserting it in front of its current one, that is, I've been trying for a long time without success, because I can't get it to pick up the positions.

0 1 2 3 4 5 6 7 8 9 
en la iteracion 1:
m
iteracion 2:(la m debe de pasar a la posicion 1 y la posicon 0 cogera la i)
i m
iteracion 3: (la i y la m se mueven una posicion por delante y la 0 tendra ahora la r)
r i m

Esta seria la salida
                  M
                  Mi
                 Mir
               Mira
              Mira 
             Mira c
           Mira có
        Mira cóm
      Mira cómo
     Mira cómo 
     ira cómo m
    ra cómo mo
    a cómo mol
     cómo mola

I leave my code I can not do it:

         char []desplazado=new char[10];
    char aux;
    byte contador=8;
   byte original=9;
            String texto = "Mira como mola esto, una marquesina";
      for (int i = 0; i < desplazado.length; i++) {

          for (int j = 0; j < desplazado.length-1; j++) {
               /*0 1 2 3 4 5 6 7 8 9
                                  m i
              */

           desplazado[original]=texto.charAt(j);
              if (original>0) {
                original--;  
              }
         aux=desplazado[original];
                   desplazado[contador]=aux;
                   if (contador>0) {
                       contador--;
                  } 
                  System.out.println(desplazado);
          }

 }

Answer:

See if this works for you. I think this way of doing it is easier than with an array .

 String frase = "Mira cómo mola esto, una marquesina";

    for(int i=0;i<=frase.length();i++) {
        if(i<10) {
            System.out.println(frase.substring(0, i));
        } else{
            System.out.println(frase.substring(i-10,i));
        }
    }

If you need to do it with an array de caracteres for something in particular the loop logic can be applied to the array well.

Scroll to Top