https://www.hackerrank.com/challenges/java-output-formatting/problem The problem link is above.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++){
String s1=sc.next();
int x=sc.nextInt();
System.out.printf("%-15s%03d\n", s1, x);
}
System.out.println("================================");
}
}
This is the answer. How do I interpret this code? Is there any other intuitive answer?
System.out.printf("%-15s%03d\n", s1, x);
%-15s%03d
The meaning of is to keep it as many as 15 digits, and 03d means padding if the given variable is less than 3 digits.
System.out.println(String.format("%-15s%03d", "abcdefghi", 5))
abcdefghi 005
I don't think there's a more efficient way than a template.
Of course there's an intuitive way.
Find out the length of s1 and if it's not 15, you can put a space until it's 15, and if x isn't 3, you can fill it with 0.
Rather than doing that, it's much better to look at and use String format's rules.
https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html
© 2024 OneMinuteCode. All rights reserved.