Java как вывести таблицу

How to print Two-Dimensional Array like table

If you don’t mind the commas and the brackets you can simply use:

System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n")); 
public class FormattedTablePrint < public static void printRow(int[] row) < for (int i : row) < System.out.print(i); System.out.print("\t"); >System.out.println(); > public static void main(String[] args) < int twoDm[][]= new int[7][5]; int i,j,k=1; for(i=0;i<7;i++) < for(j=0;j<5;j++) < twoDm[i][j]=k; k++; >> for(int[] row : twoDm) < printRow(row); >> > 

Output

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 

Of course, you might swap the 7 & 5 as mentioned in other answers, to get 7 per row.

Is there a way to use printf so I can print a table of strings with variable sizes and still have the rows/columns aligned? (e.g. the array might be <, > )

You need to print a new line after each row. System.out.print(«\n») , or use println , etc. As it stands you are just printing nothing — System.out.print(«») , replace print with println or «» with «\n» .

I’ve just replaced it and now i have and output like: 1 2 3 5 6 7 8 etc but its only vertical. what i want is like a table. anyway, thanks for the reply.

He said to put the println() after every ROW, not after every print you do. In other words, after executing the second for() loop but before allowing the first to loop around.

Make sure your println is in the correct scope. Your first print statement concatenates everything on the same line, so you need to make sure your line break happens outside the scope of the «j» for loop.

By the way. How should i make it like print 1-7 first then 8-14 etc. Im really having a hard time understanding this.

You could write a method to print a 2d array like this:

//Displays a 2d array in the console, one line per row. static void printMatrix(int[][] grid) < for(int r=0; r> 

A part from @djechlin answer, you should change the rows and columns. Since you are taken as 7 rows and 5 columns, but actually you want is 7 columns and 5 rows.

int twoDm[][]= new int[5][7]; for(i=0;i <5;i++)< for(j=0;j<7;j++) < System.out.print(twoDm[i][j]+" "); >System.out.println(""); > 

@kix: Updated my answer with array declaration as per your expectation. int twoDm[][]= new int[5][7];

@Siva Charan — it’s working now but still displaying in 1 one row. what i want is displaying it in 5 rows without using grid. thanks!

I’ll post a solution with a bit more elaboration, in addition to code, as the initial mistake and the subsequent ones that have been demonstrated in comments are common errors in this sort of string concatenation problem.

Читайте также:  Parse csv with python

From the initial question, as has been adequately explained by @djechlin, we see that there is the need to print a new line after each line of your table has been completed. So, we need this statement:

However, printing that immediately after the first print statement gives erroneous results. What gives?

This is a problem of scope. Notice that there are two loops for a reason — one loop handles rows, while the other handles columns. Your inner loop, the «j» loop, iterates through each array element «j» for a given «i.» Therefore, at the end of the j loop, you should have a single row. You can think of each iterate of this «j» loop as building the «columns» of your table. Since the inner loop builds our columns, we don’t want to print our line there — it would make a new line for each element!

Once you are out of the j loop, you need to terminate that row before moving on to the next «i» iterate. This is the correct place to handle a new line, because it is the «scope» of your table’s rows, instead of your table’s columns.

And you can see that this new line will hold true, even if you change the dimensions of your table by changing the end values of your «i» and «j» loops.

Источник

How to print the results to console in a tabular format using java?

Tabular Output

In this post, we will see how we can print the results in a table format to the standard output like the image as shown below.
To print the results like a table structure we can use either printf() or format() method.
Both the methods belong to the class java.io.PrintStream .

The printf() and format() Methods

  • The package java.io includes a PrintStream class that has two formatting methods that you can use to replace print and println . These methods format and printf are equivalent to one another.
  • The familiar System.out that you have been using happens to be a PrintStream object, so you can invoke PrintStream methods on System.out . Thus, you can use format or printf anywhere in your code where you have previously been using print or println .

I have created a domain (POJO) class called Student.java which has some basic attributes like id, emailId, name, age and grade.

 
private String id; private String name; private String emailId; private int age; private Character grade;

And the oher class is the main class to print the Student information.

  • For demonstration purpose I have created some random Student objects and added those objects to the List.
  • But in real time you may fetch the data from a Database or by calling a web service.

Below are the two classes for printing the output in tabular format.

1. Student.java

 
public class Student < private String id; private String name; private String emailId; private int age; private Character grade; // Getter and Setter methods public String getId() public void setId(String id) public String getName() public void setName(String name) public String getEmailId() public void setEmailId(String emailId) public int getAge() public void setAge(int age) public Character getGrade() public void setGrade(Character grade) // Default Constructor public Student() < super(); >// Parameterized Constructor public Student(String id, String name, String emailId, int age, Character grade) < super(); this.id = id; this.name = name; this.emailId = emailId; this.age = age; this.grade = grade; >>

2. Main.java

 
import java.util.ArrayList; import java.util.List; public class Main < public static void main(String[] args) < // Create an Empty List of Student, And add few objects to the List List&amp;amp;amp;amp;lt;Student&amp;amp;amp;amp;gt; students = new ArrayList&amp;amp;amp;amp;lt;Student&amp;amp;amp;amp;gt;(); students.add(new Student("ST001", "James Smith", "james_smith@gmail.com", 23, 'A')); students.add(new Student("ST002", "Philip Duncan", "philip_duncan@gmail.com", 22, 'c')); students.add(new Student("ST003", "Patrick Fixler", "patrick_fixler@gmail.com", 25, 'b')); students.add(new Student("ST004", "Nancy Goto", "nancy_goto@gmail.com", 24, 'A')); students.add(new Student("ST005", "Maria Hong", "maria_hong@gmail.com", 22, 'e')); // Print the list objects in tabular format. System.out.println("-----------------------------------------------------------------------------"); System.out.printf("%10s %30s %20s %5s %5s", "STUDENT ID", "EMAIL ID", "NAME", "AGE", "GRADE"); System.out.println(); System.out.println("-----------------------------------------------------------------------------"); for(Student student: students)< System.out.format("%10s %30s %20s %5d %5c", student.getId(), student.getEmailId(), student.getName(), student.getAge(), student.getGrade()); System.out.println(); >System.out.println("-----------------------------------------------------------------------------"); > >

Console Output

----------------------------------------------------------------------------- STUDENT ID EMAIL ID NAME AGE GRADE ----------------------------------------------------------------------------- ST001 james_smith@gmail.com James Smith 23 A ST002 philip_duncan@gmail.com Philip Duncan 22 c ST003 patrick_fixler@gmail.com Patrick Fixler 25 b ST004 nancy_goto@gmail.com Nancy Goto 24 A ST005 maria_hong@gmail.com Maria Hong 22 e -----------------------------------------------------------------------------

Share this:

Источник

Output in a table format in Java's System.out

I'm getting results from a database and want to output the data as a table in Java's standard output I've tried using \t but the first column I want is very variable in length. Is there a way to display this in a nice table like output?

8 Answers 8

Use System.out.format . You can set lengths of fields like this:

System.out.format("%32s%10d%16s", string1, int1, string2); 

This pads string1 , int1 , and string2 to 32, 10, and 16 characters, respectively.

See the Javadocs for java.util.Formatter for more information on the syntax ( System.out.format uses a Formatter internally).

Thanks just what I needed! I'll just add I needed to put \n at the end to produce a new line each time, in case anyone else finds that problem.

enter image description here

Using j-text-utils you may print to console a table like:

TextTable tt = new TextTable(columnNames, data); tt.printTable(); 

The API also allows sorting and row numbering .

This is sort of a pain to use, but it is nicer than continually adjusting string formatting. It'd be even better if: - the source jar was published to the Maven repo - it was in a well known repo like Central

It is too late for Greg Chabala. I am confident you have discovered a solution, but for others. Maven repo: mvnrepository.com/artifact/com.massisframework/j-text-utils/…

I may be very late for the Answer but here a simple and generic solution

import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; public class TableGenerator < private int PADDING_SIZE = 2; private String NEW_LINE = "\n"; private String TABLE_JOINT_SYMBOL = "+"; private String TABLE_V_SPLIT_SYMBOL = "|"; private String TABLE_H_SPLIT_SYMBOL = "-"; public String generateTable(ListheadersList, List rowsList,int. overRiddenHeaderHeight) < StringBuilder stringBuilder = new StringBuilder(); int rowHeight = overRiddenHeaderHeight.length >0 ? overRiddenHeaderHeight[0] : 1; Map columnMaxWidthMapping = getMaximumWidhtofTable(headersList, rowsList); stringBuilder.append(NEW_LINE); stringBuilder.append(NEW_LINE); createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping); stringBuilder.append(NEW_LINE); for (int headerIndex = 0; headerIndex < headersList.size(); headerIndex++) < fillCell(stringBuilder, headersList.get(headerIndex), headerIndex, columnMaxWidthMapping); >stringBuilder.append(NEW_LINE); createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping); for (List row : rowsList) < for (int i = 0; i < rowHeight; i++) < stringBuilder.append(NEW_LINE); >for (int cellIndex = 0; cellIndex < row.size(); cellIndex++) < fillCell(stringBuilder, row.get(cellIndex), cellIndex, columnMaxWidthMapping); >> stringBuilder.append(NEW_LINE); createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping); stringBuilder.append(NEW_LINE); stringBuilder.append(NEW_LINE); return stringBuilder.toString(); > private void fillSpace(StringBuilder stringBuilder, int length) < for (int i = 0; i < length; i++) < stringBuilder.append(" "); >> private void createRowLine(StringBuilder stringBuilder,int headersListSize, Map columnMaxWidthMapping) < for (int i = 0; i < headersListSize; i++) < if(i == 0) < stringBuilder.append(TABLE_JOINT_SYMBOL); >for (int j = 0; j < columnMaxWidthMapping.get(i) + PADDING_SIZE * 2 ; j++) < stringBuilder.append(TABLE_H_SPLIT_SYMBOL); >stringBuilder.append(TABLE_JOINT_SYMBOL); > > private Map getMaximumWidhtofTable(List headersList, List rowsList) < MapcolumnMaxWidthMapping = new HashMap<>(); for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) < columnMaxWidthMapping.put(columnIndex, 0); >for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) < if(headersList.get(columnIndex).length() >columnMaxWidthMapping.get(columnIndex)) < columnMaxWidthMapping.put(columnIndex, headersList.get(columnIndex).length()); >> for (List row : rowsList) < for (int columnIndex = 0; columnIndex < row.size(); columnIndex++) < if(row.get(columnIndex).length() >columnMaxWidthMapping.get(columnIndex)) < columnMaxWidthMapping.put(columnIndex, row.get(columnIndex).length()); >> > for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) < if(columnMaxWidthMapping.get(columnIndex) % 2 != 0) < columnMaxWidthMapping.put(columnIndex, columnMaxWidthMapping.get(columnIndex) + 1); >> return columnMaxWidthMapping; > private int getOptimumCellPadding(int cellIndex,int datalength,Map columnMaxWidthMapping,int cellPaddingSize) < if(datalength % 2 != 0) < datalength++; >if(datalength < columnMaxWidthMapping.get(cellIndex)) < cellPaddingSize = cellPaddingSize + (columnMaxWidthMapping.get(cellIndex) - datalength) / 2; >return cellPaddingSize; > private void fillCell(StringBuilder stringBuilder,String cell,int cellIndex,Map columnMaxWidthMapping) < int cellPaddingSize = getOptimumCellPadding(cellIndex, cell.length(), columnMaxWidthMapping, PADDING_SIZE); if(cellIndex == 0) < stringBuilder.append(TABLE_V_SPLIT_SYMBOL); >fillSpace(stringBuilder, cellPaddingSize); stringBuilder.append(cell); if(cell.length() % 2 != 0) < stringBuilder.append(" "); >fillSpace(stringBuilder, cellPaddingSize); stringBuilder.append(TABLE_V_SPLIT_SYMBOL); > public static void main(String[] args) < TableGenerator tableGenerator = new TableGenerator(); ListheadersList = new ArrayList<>(); headersList.add("Id"); headersList.add("F-Name"); headersList.add("L-Name"); headersList.add("Email"); List rowsList = new ArrayList<>(); for (int i = 0; i < 5; i++) < Listrow = new ArrayList<>(); row.add(UUID.randomUUID().toString()); row.add(UUID.randomUUID().toString()); row.add(UUID.randomUUID().toString()); row.add(UUID.randomUUID().toString()); rowsList.add(row); > System.out.println(tableGenerator.generateTable(headersList, rowsList)); > > 
+----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+ | Id | F-Name | L-Name | Email | +----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+ | 70a56f25-d42a-499c-83ac-50188c45a0ac | aa04285e-c135-46e2-9f90-988bf7796cd0 | ac495ba7-d3c7-463c-8c24-9ffde67324bc | f6b5851b-41e0-4a4e-a237-74f8e0bff9ab | | 6de181ca-919a-4425-a753-78d2de1038ef | c4ba5771-ccee-416e-aebd-ef94b07f4fa2 | 365980cb-e23a-4513-a895-77658f130135 | 69e01da1-078e-4934-afb0-5afd6ee166ac | | f3285f33-5083-4881-a8b4-c8ae10372a6c | 46df25ed-fa0f-42a4-9181-a0528bc593f6 | d24016bf-a03f-424d-9a8f-9a7b7388fd85 | 4b976794-aac1-441e-8bd2-78f5ccbbd653 | | ab799acb-a582-45e7-ba2f-806948967e6c | d019438d-0a75-48bc-977b-9560de4e033e | 8cb2ad11-978b-4a67-a87e-439d0a21ef99 | 2f2d9a39-9d95-4a5a-993f-ceedd5ff9953 | | 78a68c0a-a824-42e8-b8a8-3bdd8a89e773 | 0f030c1b-2069-4c1a-bf7d-f23d1e291d2a | 7f647cb4-a22e-46d2-8c96-0c09981773b1 | 0bc944ef-c1a7-4dd1-9eef-915712035a74 | +----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+ 

Источник

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