Printing columns in java

How to Print Four Columns of Data

What I can’t figure out is how do I go down 11, then go to a new column, go down 11, and so on? Thanks for the time, oh it’s java.

2 Answers 2

I’m assuming you have a 1D array that you are attempting to organize into columns for display. This can be tricky sometimes, but basically it comes down to this:

  1. Create a way to format a single element to a fixed-width string.
  2. Create a way to determine what element corresponds to a given row and column.
  3. Output one row at a time.

So, starting with the formatting, for example (pretend Element is the thing you’re trying to print):

class Element < // obviously i don't know what you're data format is; these // are just for illustrative purposes. int getIndex (); int getValue (); char getSign (); >void printElement (PrintWriter out, Element e) < // column width is 2+1+3+1+1 = 8 out.printf("%2d(%3d)%c", e.getIndex(), e.getValue(), e.getSign()); >

See Format String Syntax for more information on the format strings you can specify to PrintWriter.printf .

Then, since you can only print one row at a time, you need to be able to determine the index of the element given a row and column number. This requires you to be able to calculate the number of rows ahead of time. So say you have a ArrayList elems :

Читайте также:  Python write pipe to file

Now you output each row, one at a time, using rows as the offset between adjacent elements in a row:

PrintWriter out = System.out; // or whatever for (int r = 0; r < rows; ++ r) < for (int c = 0; c < 4; ++ c) < int index = c * rows + r; if (index < elems.size()) < printElement(out, elems.get(index)); // print data out.print(" "); // column spacer >> out.println(); // line ending after each row > 

Side note: Of course, in the (rare, these days) situation that your sole output is to a proper terminal, you could also use e.g. curses to explicitly set output row and columns on the screen. However, that’s probably not the situation you are in.

Источник

How can I print out in columns in java

I would use System.out.printf(. ) and use a template String to help be sure that all columns line up. Then you could print things out easily in a for loop.

import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class Foo4 < public static void main(String[] args) < Listbar4List = new ArrayList<>(); bar4List.add(new Bar4("Donald", 3, "A", 22.42)); bar4List.add(new Bar4("Duck", 100, "B", Math.PI)); bar4List.add(new Bar4("Herman", 20, "C", Math.sqrt(20))); String titleTemplate = "%-10s %6s %6s %9s%n"; String template = "%-10s %6d %6s %9s%n"; System.out.printf(titleTemplate, "Name", "Value", "Grade", "Cost"); for (Bar4 bar4 : bar4List) < System.out.printf(template, bar4.getName(), bar4.getValue(), bar4.getGrade(), bar4.getCostString()); >> > class Bar4 < private String name; private int value; private String grade; private double cost; private NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); public Bar4(String name, int value, String grade, double cost) < this.name = name; this.value = value; this.grade = grade; this.cost = cost; >public String getName() < return name; >public int getValue() < return value; >public String getGrade() < return grade; >public double getCost() < return cost; >public String getCostString() < return currencyFormat.format(cost); >> 
Name Value Grade Cost Donald 3 A $22.42 Duck 100 B $3.14 Herman 20 C $4.47 

For more details on the user of the String format specifiers (i.e., the %6d and %6s above), please look at the Formatter API.

Источник

Printing column using String Format in java

The following code will pretty print your data. However, you will lose the ability to properly format your floats.

/** * Pretty prints a given array of in a grid. The resolution * of the grid depends on the amount of s passed along. * * @param columns * the number of columns present in the data. * @param spacing * the number of spaces between each column. * @param objects * the objects which need to be printed. * @throws NullPointerException * when the given array of s is null. * @throws IllegalArgumentException * when there are not enough objects to fill the given amount of * columns. (i.e. objects.length must be divisible by columns). * @throws IllegalArgumentException * when the amount of spacing is smaller than zero. */ public void prettyPrint(int columns, int spacing, Object. objects) throws NullPointerException, IllegalArgumentException < if (objects == null) throw new NullPointerException( "the given array of objects is null!"); if (objects.length % columns != 0) throw new IllegalArgumentException( "not enough objects are passed along to fill the columns!"); if (spacing < 0) throw new IllegalArgumentException( "the amount of spacing should be larger than zero!"); int rows = objects.length / columns; // convert all objects to strings String[] strings = new String[objects.length]; for (int i = 0; i < objects.length; ++i) strings[i] = objects[i].toString(); // determine the maximum length of the items in each column int totalLength = 0; int[] maxLength = new int[columns]; for (int column = 0; column < columns; ++column) < int maximum = 0; for (int row = 0; row < rows; ++row) maximum = Math.max(maximum, strings[column + row * columns].length()); maxLength[column] = maximum; totalLength += maximum; >// determine the total width of the output string (this is the sum of // maximum lengths of each column + the length caused by adding // (columns-1) spaces between the columns. totalLength += (columns - 1) * spacing; // print the header System.out.println(repeat("-", totalLength)); for (int row = 0; row < rows; ++row) < for (int column = 0; column < columns; ++column) < // print the string String string = strings[column + row * columns]; System.out.print(string); // print the spaces except after the element in the last column if (column < columns - 1) < int spaces = maxLength[column] - string.length() + spacing; System.out.print(repeat(" ", spaces)); >> System.out.println(); > // print the footer System.out.println(repeat("-", totalLength)); > /** * Repeats the given n times. * * @param str * the to repeat. * @param n * the repetition count. * @throws IllegalArgumentException * when the given repetition count is smaller than zero. * @return the given repeated n times. */ public static String repeat(String str, int n) < if (n < 0) throw new IllegalArgumentException( "the given repetition count is smaller than zero!"); else if (n == 0) return ""; else if (n == 1) return str; else if (n % 2 == 0) < String s = repeat(str, n / 2); return s.concat(s); >else return str.concat(repeat(str, n - 1)); > /** * Repeats the given n times. * * @param str * the to repeat. * @param n * the repetition count. * @throws IllegalArgumentException * when the given repetition count is smaller than zero. * @return the given repeated n times. */ public static String repeat(String str, int n) < if (n < 0) throw new IllegalArgumentException( "the given repetition count is smaller than zero!"); else if (n == 0) return ""; else if (n == 1) return str; else if (n % 2 == 0) < String s = repeat(str, n / 2); return s.concat(s); >else return str.concat(repeat(str, n - 1)); > 
prettyPrint(4, 2, "", "qty", "price", "code", "Coffee", 2, 12.000, "T1", "Tea", 1, 10.000, "T1", "Orange Juice", 1, 15.000, "T1", "Juice", "", "", "", "Tap Water", 1, 9000, "T1"); 
------------------------------ qty price code Coffee 2 12.0 T1 Tea 1 10.0 T1 Orange Juice 1 15.0 T1 Juice Tap Water 1 9000 T1 ------------------------------ 

Источник

how to print columns in java txt file

I am trying to print multiple arrays on one .txt file having one array print then have another column crated and have another array print how do i format this to work?? I cant remember the formatting commands to do this I need all the columns to align right now i have this

private static void makeFile(String[] name, String[] nickname, String[] capital, String[] flowers, String[] population) throws FileNotFoundException

enter image description here

This is what prints How do i fix it so they are all aligned and there are 3 more columns to add to this how do i get them to align as well ??

If alignment is the issue, I would suggest you use a fixed valued length allowed in first column, say 50 or 60, then for each iteration , calculate the space between them as 50 — length of the name

4 Answers 4

You should use String.format like

String.format("%-30s %s", name[i], nickname[i]) 

where 30 is maximum length of name.

You can use printf instead of println , with C-style format strings.

out.printf("%-16s%-24s\n", name[i], nickname[i]); 

This will print the name[i] left-aligned in a 16-character placeholder, then print nickname[i] in a 24-character wide column. When adding more columns, you can specify the maximum required number of characters in the format string. The — sign is added for aligning the strings to left.

You could do something like this

// Get the maximum length of any string in the array, or 0. private static int getMaxLength(String[] in) < int c = 0; if (in != null && in.length >0) < for (String i : in) < i = (i != null) ? i.trim() : ""; if (i.length() >c) < c = i.length(); >> > return c; > // Pad any input string to the minimum length. private static String padString(String in, int min) < in = (in != null) ? in.trim() : ""; StringBuilder sb = new StringBuilder(in); while (sb.length() < min) < sb.append(' '); >return sb.toString(); > private static void makeFile(String[] name, String[] nickname, String[] capital, String[] flowers, String[] population) < PrintWriter out = null; try < out = new PrintWriter("out.txt"); // Add 1 to get at least 1 space between the maximum and the next item. int namePadded = getMaxLength(name) + 1; int nickPadded = getMaxLength(nickname) + 1; int capitalPadded = getMaxLength(capital) + 1; int flowersPadded = getMaxLength(flowers) + 1; int populationPadded = getMaxLength(population); for (int i = 0; i < name.length; i++) < out.println(padString(name[i], namePadded) + padString((nickname.length >i) ? nickname[i] : "", nickPadded) + padString((capital.length > i) ? capital[i] : "", capitalPadded) + padString((flowers.length > i) ? flowers[i] : "", flowersPadded) + padString((population.length > i) ? population[i] : "", populationPadded)); > > catch (FileNotFoundException fnfe) < fnfe.printStackTrace(System.err); >finally < out.close(); >> public static void main(String[] args) < String[] name = < "Alabama", "Alaska", "Arizona" >; String[] nickname = < "Yellowhammer State", "Last Frontier", "Grand Canyon State" >; String[] capital = < "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "Y", "Z" >; String[] flowers = < "Rose", "Carnation", "Orchid" >; String[] population = < "1", "100", "1000" >; makeFile(name, nickname, capital, flowers, population); > 

Источник

Is there an easy way to output two columns to the console in Java?

As the title says, is there an easy way to output two columns to the console in Java? I’m aware of \t , but I haven’t found a way to space based on a specific column when using printf.

3 Answers 3

Use the width and precision specifiers, set to the same value. This will pad strings that are too short, and truncate strings that are too long. The ‘-‘ flag will left-justify the values in the columns.

System.out.printf("%-30.30s %-30.30s%n", v1, v2); 

But for this kind of statement we can’t apply that. str += «\t » + item.getName() + » [» + item.getValue() + «]» + «\t» + item.getDescription()+ «\n»; what should we do for this situation?

@chamzz.dot Use String.format() instead of concatenating strings. It looks like you are using that in a loop which can have quadratic time complexity (in other words, that’s bad). Instead, make str a StringBuilder outside your loop, and append() the result of each String.format() call inside the loop.

i did it without using Formatter class as :

 System.out.printf("%-10s %-10s %-10s\n", "osne", "two", "thredsfe"); System.out.printf("%-10s %-10s %-10s\n", "one", "tdsfwo", "thsdfree"); System.out.printf("%-10s %-10s %-10s\n", "onsdfe", "twdfo", "three"); System.out.printf("%-10s %-10s %-10s\n", "odsfne", "twsdfo", "thdfree"); System.out.printf("%-10s %-10s %-10s\n", "osdne", "twdfo", "three"); System.out.printf("%-10s %-10s %-10s\n", "odsfne", "tdfwo", "three"); 
osne two thredsfe one tdsfwo thsdfree onsdfe twdfo three odsfne twsdfo thdfree osdne twdfo three odsfne tdfwo three 

Late answer but if you don’t want to hardcode the width, how about something that works like this:

public static void main(String[] args)
One Two Three Four 1 2 3 4 
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Columns < List> lines = new ArrayList<>(); List maxLengths = new ArrayList<>(); int numColumns = -1; public Columns addLine(String. line) < if (numColumns == -1)< numColumns = line.length; for(int column = 0; column < numColumns; column++) < maxLengths.add(0); >> if (numColumns != line.length) < throw new IllegalArgumentException(); >for(int column = 0; column < numColumns; column++) < int length = Math .max( maxLengths.get(column), line[column].length() ) ; maxLengths.set( column, length ); >lines.add( Arrays.asList(line) ); return this; > public void print() < System.out.println( toString() ); >public String toString() < String result = ""; for(Listline : lines) < for(int i = 0; i < numColumns; i++) < result += pad( line.get(i), maxLengths.get(i) + 1 ); >result += System.lineSeparator(); > return result; > private String pad(String word, int newLength) < while (word.length() < newLength) < word += " "; >return word; > > 

Since it won’t print until it has all the lines, it can learn how wide to make the columns. No need to hard code the width.

Источник

Оцените статью