Home > Net >  dynamic spacing with printf in Java
dynamic spacing with printf in Java

Time:12-02

I have the following code, which works but the dynamic spacing seems pretty cluegy. Is there a more direct approach?

public class BubbleSort{
    static int[] unsorted = new int[10];
    public static void main(String[] args)throws InterruptedException{
          clearScreen();        
          
          for(int i = 0; i < 10; i  ){
              unsorted[i] = (int) (Math.random() * 100);
          }
          
          printArray();
          Thread.sleep(3000);
          int x = 0;
          String space=" ";
          
          
          for (int i = 0; i < unsorted.length - 1; i  ){
              for(int j = 0; j < unsorted.length - 1 - i; j  ){
                  
                  if(unsorted[j] > unsorted[j 1]){
                      int temp = unsorted[j];
                      unsorted[j] = unsorted[j 1];
                      unsorted[j 1] = temp;                                            
                  }
                  if(x == 0) System.out.printf("\n"   "-  -\n",j,(j 1));
                  else System.out.printf("\n%"  x   "s-  -\n",space,j,(j 1));
                  x =4;
                  if(x > 34)x = 0;
                  printArray();
                  Thread.sleep(1000);
                  System.out.println();
              }              
          }
    }
}
       

CodePudding user response:

You could create the "spacer" dynamically, instead of printing a fixed-length spacer with offset. So instead of

if(x == 0) System.out.printf("\n"   "-  -\n",j,(j 1));
else System.out.printf("\n%"  x   "s-  -\n",space,j,(j 1));

do this:

System.out.printf("%n%s-  -%n", space.repeat(x), j, (j   1));
  • Related