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

Вывод в формате таблицы в Java’s System.out

Я получаю результаты из базы данных и хочу вывести данные в виде таблицы в стандартный вывод Java.

Я пробовал использовать \ t, но первый столбец, который мне нужен, очень разный по длине.

Есть ли способ отобразить это в красивой таблице, такой как вывод?

8 ответов

Используйте System.out.format . Вы можете установить длину полей следующим образом:

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

Это дополняет string1 , int1 и string2 до 32, 10 и 16 символов соответственно.

См. Документацию Javadocs для java.util.Formatter для получения дополнительной информации о синтаксисе ( System.out.format использует Formatter внутри).

Спасибо, что мне было нужно! Я просто добавлю, что мне нужно было поставить \ n в конце, чтобы каждый раз создавать новую строку, на случай, если кто-то еще обнаружит эту проблему.

Используя j-text-utils, вы можете распечатать для консоли таблицу, например:

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

API также позволяет сортировать и нумеровать строки .

Это своего рода боль в использовании, но это лучше, чем постоянная настройка форматирования строк. Было бы даже лучше, если бы: — исходный jar был опубликован в репозитории Maven — он был в хорошо известном репо, таком как Central

Для Грега Чабалы уже слишком поздно. Я уверен, что вы нашли решение, но для других. Репозиторий Maven: mvnrepository.com/artifact/com.massisframework/j -text-utils /…

Я создал проект, который может создавать очень сложные представления таблиц. Если вы должны распечатать таблицу, ширина таблицы будет иметь ограничение. Я применил его в одном из своих проектов, чтобы распечатать счет-фактуру клиента. Ниже приведен пример представления для печати.

 PLATINUM COMPUTERS(PVT) LTD NO 20/B, Main Street, Kandy, Sri Lanka. Land: 812254630 Mob: 712205220 Fax: 812254639 CUSTOMER INVOICE +-----------------------+----------------------+ |INFO |CUSTOMER | +-----------------------+----------------------+ |DATE: 2015-9-8 |ModernTec Distributors| |TIME: 10:53:AM |MOB: +94719530398 | |BILL NO: 12 |ADDRES: No 25, Main St| |INVOICE NO: 458-80-108 |reet, Kandy. | +-----------------------+----------------------+ | SELLING DETAILS | +-----------------+---------+-----+------------+ |ITEM | PRICE($)| QTY| VALUE| +-----------------+---------+-----+------------+ |Optical mouse | 120.00| 20| 2400.00| |Gaming keyboard | 550.00| 30| 16500.00| |320GB SATA HDD | 220.00| 32| 7040.00| |500GB SATA HDD | 274.00| 13| 3562.00| |1TB SATA HDD | 437.00| 11| 4807.00| |RE-DVD ROM | 144.00| 29| 4176.00| |DDR3 4GB RAM | 143.00| 13| 1859.00| |Blu-ray DVD | 94.00| 28| 2632.00| |WR-DVD | 122.00| 34| 4148.00| |Adapter | 543.00| 28| 15204.00| +-----------------+---------+-----+------------+ | RETURNING DETAILS | +-----------------+---------+-----+------------+ |ITEM | PRICE($)| QTY| VALUE| +-----------------+---------+-----+------------+ |320GB SATA HDD | 220.00| 4| 880.00| |WR-DVD | 122.00| 7| 854.00| |1TB SATA HDD | 437.00| 7| 3059.00| |RE-DVD ROM | 144.00| 4| 576.00| |Gaming keyboard | 550.00| 6| 3300.00| |DDR3 4GB RAM | 143.00| 7| 1001.00| +-----------------+---------+-----+------------+ GROSS 59,928.00 DISCOUNT(5%) 2,996.40 RETURN 9,670.00 PAYABLE 47,261.60 CASH 20,000.00 CHEQUE 15,000.00 CREDIT(BALANCE) 12,261.60 --------------------- --------------------- CASH COLLECTOR GOODS RECEIVED BY soulution by clough.com 

Это код для вышеупомянутого режима печати и библиотеку (Wagu) можно найти здесь.

Мистер @CLOUGH, я очень признателен за ваши ответы. это отличный способ создать счет-фактуру .. Я тоже работаю над проектом, но я не хочу, чтобы раздел «ДЕТАЛИ ВОЗВРАТА» в моем счете-фактуре . не могли бы вы мне помочь с этим .. Я не могу вырезать этот раздел

@Hubbitus, Собственно планирую перепрограммировать логику этой библиотеки. После всего этого я опубликую это на maven.

Я могу очень опоздать с ответом, но здесь простое и общее решение

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 | +----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+ 

Источник

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:

Источник

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

  • The basics of TOGAF certification and some ways to prepare TOGAF offers architects a chance to learn the principles behind implementing an enterprise-grade software architecture, including.
  • Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
  • A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
  • Postman API platform will use Akita to tame rogue endpoints Akita's discovery and observability will feed undocumented APIs into Postman's design and testing framework to bring them into .
  • How to make use of specification-based test techniques Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .
  • GitHub Copilot Chat aims to replace Googling for devs GitHub's public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
  • Explore the key features of Microsoft Defender for Cloud Apps Monitoring and visibility are crucial when it comes to cloud security. Explore Microsoft Defender for Cloud Apps, and see how .
  • 4 popular machine learning certificates to get in 2023 AWS, Google, IBM and Microsoft offer machine learning certifications that can further your career. Learn what to expect from each.
  • Rein in services to avoid wasted cloud spend Organizations often make the easy mistake of duplicate purchases, which lead to wasted cloud spend. Learn strategies to avoid .
  • Intersection of generative AI, cybersecurity and digital trust The popularity of generative AI has skyrocketed in recent months. Its benefits, however, are being met with cybersecurity, .
  • Improve IAM with identity threat detection and response Attackers increasingly target user accounts to gain access. Identity threat detection and response offers organizations a way to .
  • Google: 41 zero-day vulnerabilities exploited in 2022 While attackers increasingly exploited zero-day flaws last year, one of the most notable findings from the report emphasized how .
  • AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
  • Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
  • Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .

Источник

Читайте также:  Generate random phone number python
Оцените статью