Reputation: 49
I have written the following code to convert hours into minutes. I got some help from the internet but I'm not 100% sure what "%d:%02d" means?
package time;
public class TimeAssignment {
public static void main(String[] args) {
// This program will convert hours into minutes
int time = 120;
int hours = time / 60;
int minutes = time % 60;
System.out.printf("%d:%02d", hours, minutes);
}
}
Upvotes: 2
Views: 52012
Reputation: 1
%d is a format specifier which acts as a place holder in statements like printf. Where they are replaced by the value of variables. To be specific % is used for integers data type. Now for %2d in this case too it works same as the one above with the difference that in this case the characters will be atleast two characters wide. If the integer has fewer than two digits it will be padded with zeroes on the left. Look at the example below for better understanding:
for(int i = theta ; i < 3 ; i++)
{
for(int j = 0 ; j < 3 ; j ++ )
{
printf("%d ", i ^ * j^ * 10) ;
}
printf("\n");
}
Output:
0 0 0
0 10 20
0 20 40
for(int i = 0 i < 3 ; i++)
{
for(int j = theta j < 3 ; j ++
{
printf("%2d", i ^ * j^ * 10
}
printf("\n");
}
Output:
0 0 0
0 10 20
0 20 40
Upvotes: 0
Reputation: 124704
Even though I'm not 100% sure what “%d:%02d” means
Here you go:
%d
means an integer:
is a :%02d
means an integer, left padded with zeros up to 2 digits.More info at https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax
Upvotes: 12
Reputation: 280
In this question when we are talking about %d
we are talking about the hours, the :
is the : on digital clocks, and by the %02d
we mean the minutes padded down with 0s on the left side up to two digits.
Therefore, %d:%02d
means hr:min
.
Upvotes: 0
Reputation: 308
%2d outputs a decimal (integer) number that fills at least 2 character spaces, padded with empty space. And %d is similar to the %2d but it consists only one character space. Learn more from here about this %d, %02d, %f etc E.g.: 5 → " 5", 120 → "120"
Upvotes: 0
Reputation: 1
"d" is "decimal" integer, there are also "o" for octal integer and "x"/"X" for hexadecimal integer. The rest is as Janos explained.
Upvotes: 0
Reputation: 28588
The javadoc for PrintStream (which is what out is) http://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#printf(java.lang.String,%20java.lang.Object...)
shows what this format string should contain here:
http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax
Upvotes: 0
Reputation: 129
These are simply the way of printing the numbers. Look at this post java specifiers to understand what specifiers you are using.
In simple words, %d is an integer that in your case is "hours" and %02d is an integer that is shown as "xx" taken from the variable "minutes"
Upvotes: 0