This question already has an answer here:
I am trying to format in java using the printf statement like in this webpage: Click Here. But I just can't figure out what the purpose of the $ sign is. Can someone please explain this to me?
Input:
java 100
cpp 65
python 50
Expected Output: ( there should be a space instead of _ )
================================
java___________100
cpp___________065
python_________050
================================
My code:
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(s1 + "%03d", x);
System.out.println();
}
System.out.println("================================");
}
}
It is the Argument Index. You can read the docs. I will try to explain the string from the tutorial for you:
In general the format is
%[argument_index$][flags][width][.precision]conversion
.In our example,
#$
points to the position within ourprintft()
statement. We have 3 strings to be formatted and hence why our format string has1$
,2$
,3$
. The number that follows its the width between each argument. This width begins at 0 which means the actual width would be +1. Thes
is our conversion to string and the%n
new line at the end.