java formatted output

java formatted output

In Java, you can use the printf() method of the PrintStream class or the format() method of the String class to produce formatted output.

Here's an example of how to use the printf() method to produce formatted output:

public class Main {
  public static void main(String[] args) {
    int value = 123;
    double ratio = 0.456;

    // Print a formatted string to the console
    System.out.printf("Value: %d, Ratio: %.2f", value, ratio);
  }
}
S‮cruo‬e:www.lautturi.com

This code uses the printf() method of the System.out object to print a formatted string to the console. The format string contains two format specifiers: %d specifies that an integer value should be formatted, and %.2f specifies that a floating-point value should be formatted with two decimal places. The values to be formatted (value and ratio) are provided as arguments to the printf() method.

The printf() method replaces each occurrence of a format specifier in the format string with the corresponding value, and produces a formatted string as output.

Here's an example of how to use the format() method of the String class to produce formatted output:

public class Main {
  public static void main(String[] args) {
    int value = 123;
    double ratio = 0.456;

    // Create a formatted string
    String formattedString = String.format("Value: %d, Ratio: %.2f", value, ratio);

    System.out.println(formattedString); // prints "Value: 123, Ratio: 0.46"
  }
}

This code uses the format() method of the String class to create a formatted string, using the same format string and values as in the previous example. The format() method returns the formatted string as a result, which can then be printed to the console using the println() method of the System.out object.

You can find more information about the printf() and format() methods and the available format specifiers in the Java documentation.

Created Time:2017-11-03 22:21:06  Author:lautturi