Форматирование вывода с помощью printf() в Java
Этот метод является частью класса java.io.PrintStream и обеспечивает форматирование строк, аналогичное функции printf() в C.
2. Синтаксис
Мы можем использовать один из этих методов PrintStream для форматирования вывода:
System.out.printf(format, arguments); System.out.printf(locale, format, arguments);
Мы указываем правила форматирования с помощью параметра формата . Правила начинаются с символа % .
Давайте рассмотрим краткий пример, прежде чем углубляться в детали различных правил форматирования:
System.out.printf("Hello %s!%n", "World");
Это дает следующий результат:
Как показано выше, строка формата содержит обычный текст и два правила форматирования. Первое правило используется для форматирования строкового аргумента. Второе правило добавляет символ новой строки в конец строки.
2.1. Правила формата
Давайте посмотрим на строку формата более внимательно. Он состоит из литералов и спецификаторов формата. Спецификаторы формата включают флаги, ширину, точность и символы преобразования в этой последовательности:
%[flags][width][.precision]conversion-character
Спецификаторы в скобках являются необязательными.
Внутри printf() использует класс java.util.Formatter для разбора строки формата и создания вывода. Дополнительные параметры строки формата можно найти в Javadoc Formatter .
2.2. Преобразование символов
Символ преобразования является обязательным и определяет формат аргумента.
Символы преобразования допустимы только для определенных типов данных. Вот некоторые из них:
- s форматирует строки.
- d форматирует десятичные целые числа.
- f форматирует числа с плавающей запятой.
- t форматирует значения даты/времени.
Мы рассмотрим их и некоторые другие позже в этом руководстве.
2.3. Дополнительные модификаторы
[ Флаги `] ` определяют стандартные способы изменения вывода и чаще всего используются для форматирования целых чисел и чисел с плавающей запятой.
[width] указывает ширину поля для вывода аргумента. Он представляет собой минимальное количество символов, записываемых на выходе.
[.precision] указывает количество разрядов точности при выводе значений с плавающей запятой. Кроме того, мы можем использовать его для определения длины подстроки для извлечения из String .
3. Разделитель строк
Чтобы разбить строку на отдельные строки, у нас есть спецификатор % n :
System.out.printf("foreach%nline%nterminator");
Приведенный выше фрагмент кода выдаст следующий результат:
Formatting
Stream objects that implement formatting are instances of either PrintWriter , a character stream class, or PrintStream , a byte stream class.
Note: The only PrintStream objects you are likely to need are System.out and System.err . (See I/O from the Command Line for more on these objects.) When you need to create a formatted output stream, instantiate PrintWriter , not PrintStream .
Like all byte and character stream objects, instances of PrintStream and PrintWriter implement a standard set of write methods for simple byte and character output. In addition, both PrintStream and PrintWriter implement the same set of methods for converting internal data into formatted output. Two levels of formatting are provided:
- print and println format individual values in a standard way.
- format formats almost any number of values based on a format string, with many options for precise formatting.
The print and println Methods
Invoking print or println outputs a single value after converting the value using the appropriate toString method. We can see this in the Root example:
Here is the output of Root :
The square root of 2 is 1.4142135623730951. The square root of 5 is 2.23606797749979.
The i and r variables are formatted twice: the first time using code in an overload of print , the second time by conversion code automatically generated by the Java compiler, which also utilizes toString . You can format any value this way, but you don’t have much control over the results.
The format Method
The format method formats multiple arguments based on a format string. The format string consists of static text embedded with format specifiers; except for the format specifiers, the format string is output unchanged.
Format strings support many features. In this tutorial, we’ll just cover some basics. For a complete description, see format string syntax in the API specification.
The Root2 example formats two values with a single format invocation:
The square root of 2 is 1.414214.
Like the three used in this example, all format specifiers begin with a % and end with a 1- or 2-character conversion that specifies the kind of formatted output being generated. The three conversions used here are:
- d formats an integer value as a decimal value.
- f formats a floating point value as a decimal value.
- n outputs a platform-specific line terminator.
Here are some other conversions:
- x formats an integer as a hexadecimal value.
- s formats any value as a string.
- tB formats an integer as a locale-specific month name.
There are many other conversions.
Except for %% and %n , all format specifiers must match an argument. If they don’t, an exception is thrown.
In the Java programming language, the \n escape always generates the linefeed character ( \u000A ). Don’t use \n unless you specifically want a linefeed character. To get the correct line separator for the local platform, use %n .
In addition to the conversion, a format specifier can contain several additional elements that further customize the formatted output. Here’s an example, Format , that uses every possible kind of element.
3.141593, +00000003.1415926536
The additional elements are all optional. The following figure shows how the longer specifier breaks down into elements.
Elements of a Format Specifier.
The elements must appear in the order shown. Working from the right, the optional elements are:
- Precision. For floating point values, this is the mathematical precision of the formatted value. For s and other general conversions, this is the maximum width of the formatted value; the value is right-truncated if necessary.
- Width. The minimum width of the formatted value; the value is padded if necessary. By default the value is left-padded with blanks.
- Flags specify additional formatting options. In the Format example, the + flag specifies that the number should always be formatted with a sign, and the 0 flag specifies that 0 is the padding character. Other flags include — (pad on the right) and , (format number with locale-specific thousands separators). Note that some flags cannot be used with certain other flags or with certain conversions.
- The Argument Index allows you to explicitly match a designated argument. You can also specify < to match the same argument as the previous specifier. Thus the example could have said: System.out.format("%f, %
Java print string with format
- 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 .
- Navigate multi-cloud billing challenges Keeping track of cloud bills from multiple clouds or accounts can be complex. Learn how to identify multi-cloud billing .
- 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
- How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
- BrightTALK @ Black Hat USA 2022 BrightTALK’s virtual experience at Black Hat 2022 included live-streamed conversations with experts and researchers about the .
- The latest from Black Hat USA 2023 Use this guide to Black Hat USA 2023 to keep up on breaking news and trending topics and to read expert insights on one of the .
- API keys: Weaknesses and security best practices API keys are not a replacement for API security. They only offer a first step in authentication — and they require additional .
- 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 .