Java 17 Recipes


-16. Making a String That Can Contain Dynamic


Download 3.2 Mb.
Pdf ko'rish
bet64/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   60   61   62   63   64   65   66   67   ...   245
Bog'liq
Java 17 Recipes

3-16. Making a String That Can Contain Dynamic
Information
 Problem
You want to generate a string that can contain a dynamic placeholder such that the string 
can change depending on application data variations.
 Solution 1
Utilize the built-in format() method for generating a string containing placeholders for 
dynamic data. The following example demonstrates a string that contains a dynamic 
placeholder that allows different data to be inserted into the same string. As the 
temperature variable changes, the string is dynamically altered.
public static void main(String[] args){
double temperature = 37.1;
String temperatureString = "The current temperature is %.1f degrees 
Celsius.";
System.out.println(String.format(temperatureString, temperature));
temperature = 38.4;
System.out.println(String.format(temperatureString, temperature));
}
It returns the following output.
The current temperature is 37.1 degrees Celsius.
The current temperature is 38.4 degrees Celsius.
 Solution 2
If you wish to print the contents of the string out, rather than store them for later use, 
the System.out.printf() method can position dynamic values within a string. The 
following example demonstrates the same concept as that in solution 1, except this time
Chapter 3 StringS


105
rather than using the String.format() method, a string is simply printed out, and the 
placeholders passed to the System.out.printf() method are replaced with the dynamic 
content at runtime.
public static void main(String[] args){
double temperature = 37.1;
System.out.printf("The current temperature is %.1f degrees Celsius.\n", 
temperature);
temperature = 38.4;
System.out.printf("The current temperature is %.1f degrees Celsius.", 
temperature);
}
It returns the following output.
The current temperature is 37.1 degrees Celsius.
The current temperature is 38.4 degrees Celsius.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   60   61   62   63   64   65   66   67   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling