I tried to work with easy example of java.util.Formatter
class.
To my mind it works exactly as System.out.printf()
.
But my easy program show unexpected result.
Can smb explain why?
Expected is at the single line name of field: and value of this value.
Code:
class DataHolder {
int i=145;
long l = 789L;
float f = 78.8F;
double d = 34.9;
public String toString() {
StringBuilder sb = new StringBuilder("DataHolder class: \n\n");
Formatter formatter = new Formatter(Locale.US);
sb.append(formatter.format("int field: %d\n", i));
sb.append(formatter.format("long field: %d\n", l));
sb.append(formatter.format("float field: %f\n", f));
sb.append(formatter.format("double field: %f\n", d));
return sb.toString();
}
}
public class Test {
public static void main(String[] args) {
System.out.println(new DataHolder());
}
}
Output:
DataHolder class:
int field: 145
int field: 145
long field: 789
int field: 145
long field: 789
float field: 78.800003
int field: 145
long field: 789
float field: 78.800003
double field: 34.900000
Why we can see here duplicates of lines, and some of them isn't correct.
What is wrong and how to work correctly with Formatter
?