简体   繁体   中英

Printing arrays on single line in Java

I'm trying to make a 'histogram' in java and running into trouble with some formatting. I've got the below loop for printing a frequency distribution table:

for (int i = 0; i < 10; i++) {
        char asterisk[] = new char[frequency[i]];
        Arrays.fill(asterisk, '*');
        System.out.println(asterisk);
        freqTable = bins[i] + "\t";
        System.out.println(freqTable);
    }

But this produces an output like:

************
1-10    
**********
11-20   
**********
21-30

And i'd like to have it print like this:

1-10 ************
11-20 **********
21-30 **********

No idea how to get it to do this! Tried using toString(), didn't get anywhere though.

Thanks in advance!

You need to re-order the statements that print your items. I would recommend using a single println at the end of the loop:

for (int i = 0; i < 10; i++) {
    char asterisk[] = new char[frequency[i]];
    Arrays.fill(asterisk, '*');
    System.out.println(bins[i] + "\t" + asterisk);
}

Simply change the order and using print instead of println

for (int i = 0; i < 10; i++) {
    char asterisk[] = new char[frequency[i]];
    Arrays.fill(asterisk, '*');
    freqTable = bins[i] + "\t";
    System.out.print(freqTable);
    System.out.println(asterisk);
}

or alternative use System.out.printf

System.out.printf ("%s %s%n", freqTable, asterisk);

or a single System.out.println

System.out.println(freqTable + asterisk);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM