Abdullah Khan
Abdullah Khan

Reputation: 59

How can I print the results of 2 for loops on the same line

I am trying to get the code to run so that the output looks like this,

91-100 | [][][][][][][][][]

81- 90 | [][][][][]

71- 80 | [][][][][][][][][][]

61- 70 | [][]

51- 60 | []

41- 50 | [][]

31- 40 |

21- 30 |

11- 20 |

 1- 10 | [][][]

But currently, my output is looking like this,

91-100 |

[][][][][][][][][]81- 90 |

[][][][][]71- 80 |

[][][][][][][][][][]61- 70 |

[][]51- 60 |

[]41- 50 |

[][]31- 40 |

21- 30 |

11- 20 |

 1- 10 |

[][][]

Here is my code:

 int[] buckets = new int[10];
 while(scan.hasNextLine()){            
     String line = scan.nextLine();
     String[] array = line.split(separator);
     String grade = array[1];
     int number =  Integer.parseInt(grade.trim());
     buckets[(number - 1)/10]++;           
 }
 for(int i = buckets.length - 1; i >= 0; i--)// RELEVANT PARTS TO QUESTION
     System.out.printf("%2d-%3d |%n", i * 10 + 1, i * 10 + 10);
     for(int j = 0; j < buckets[i]; j++){
         System.out.print("[]");
     }
 } 

I seem to be printing the [] on to the next line, but I can't seem to figure out how to put the [] on the line above. I tried using printf(%d %d | %s%n), but that doesnt work too well from what i have tried and just creates more problems. Is there anyway to move the [] back a line?

Upvotes: 3

Views: 2442

Answers (3)

Bashima
Bashima

Reputation: 122

System.out.printf() and System.out.println() add a new line at the end. So just use System.out.print() and at the end of a line use System.out.println()

for(int i = buckets.length - 1; i >= 0; i--)// RELEVANT PARTS TO QUESTION
    System.out.print("%2d-%3d |", i * 10 + 1, i * 10 + 10);
    for(int j = 0; j < buckets[i]; j++){
        System.out.print("[]");
    }
    System.out.println();
} 

Upvotes: 0

Michael Lihs
Michael Lihs

Reputation: 8220

You can create the bucket string before the printf statement and then print the string at once like

 for (int i = buckets.length - 1; i >= 0; i--) {        
     String bucketsString = "";    

     for(int j = 0; j < buckets[i]; j++) 
         bucketsString = bucketsString.concat("[]");

     System.out.printf("%2d-%3d | %s %n", i * 10 + 1, i * 10 + 10, bucketsString);
 } 

Upvotes: 2

ScegfOd
ScegfOd

Reputation: 402

Since printf prints a new line when you enter %n, I suggest using something like this (replace %n with a space, add println after the loop):

for(int i = buckets.length - 1; i >= 0; i--) {
    System.out.print("%2d-%3d | ", i * 10 + 1, i * 10 + 10);
    for(int j = 0; j < buckets[i]; j++){
        System.out.print("[]");
    } 
    System.out.println("");
}

the println statement will give you the newline in the place you want.

Upvotes: 1

Related Questions