Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // import java.lang.Math; // Activate if needed
- import java.time.LocalDateTime;
- import java.util.ArrayList;
- import java.util.Locale;
- public class str_format {
- public static void main(String[] args) {
- // String format: %[parameter_index$][flags][width][.precision]conversion_target
- String name = "tony stark";
- String city = "bogor";
- String movie = "avengers";
- String job = "worker";
- ArrayList<String> index = new ArrayList<String>(); // CREATE ARRAY
- // EXAMPLE: 1
- index.add(String.format("name is %s, live in %S", name, city));
- index.add(String.format("name is %1$s, live in %2$S watch %3$s job: %4$s %n", name, city, movie, job)); // POSITION (index)
- index.add(String.format("To be integer %40d others way", (int) Math.round(101.99)));
- index.add(String.format("To be integer %,d others way", -1010987654));
- index.add(String.format(Locale.ITALY, "To be integer %,d local", 1010987654));
- index.add(String.format(Locale.ITALY, "To be precision %,.3f local", -10109.87654)); // PRECISION
- index.add(String.format(Locale.ITALY, "To be zero float %,.0f local", -10109.87654));
- index.add(String.format("value is %f", 32.33434));
- index.add(String.format("value is %32.12f", 32.33434)); //returns 12 char fractional part filling with 0
- // EXAMPLE: 2
- index.add(String.format("Integer %d", 101));
- index.add(String.format("String %s", "great person: Muhammad"));
- index.add(String.format("Float %,f", 1_000_101.00));
- index.add(String.format("Hexadecimal %x", 101));
- index.add(String.format("Char %c", 'c'));
- // EXAMPLE: 3
- index.add(String.format("%d", 101));
- index.add(String.format("|%10d|", 101)); // Specifying length of integer
- index.add(String.format("|%-10d|", 101)); // Left-justifying within the specified width
- index.add(String.format("|% d|", 101));
- index.add(String.format("|%010d|", 101)); // Filling with zeroes
- index.add(String.format("To be integer %d", (int) 101.99));
- index.add(String.format("To be integer %d other way", (int) Math.round(101.99)));
- index.add(String.format("To be integer %40d others way", (int) Math.round(101.99))); // flags
- // DATE TIME EXAMPLE
- LocalDateTime today = LocalDateTime.now();
- index.add(String.format("Today is %tA", today));
- index.add(String.format("Full date is %1$tA year %1$tY month %1$tm date %1$tm", today));
- index.add(String.format("short date is %1$td.%1$tm.%1$ty %n", today));
- index.add(String.format("Time is hours %tH: minutes %tM: seconds %tS %n", today, today, today));
- for (String result : index) {
- System.out.println(result);
- }
- }
- }
Add Comment
Please, Sign In to add comment