ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
hi,all:
I met a trouble in Java, that is the method of "Formatter.format".
The "System.out.printf" can output what I want,
but why can't "Formatter.format" do that in the under way ?
(JDK_1.6)
Code:
Formatter formatter = new Formatter();
int i = 0, j = 0;
float[][] fy = {{1.1f,2.1f,3.1f},
{2.7f,2.4f,6.3f},
{7.1f,8.1f,9f}};
for(i=0;i<3;i++) {
for( j=0;j<3;j++) {
//System.out.printf("%.1f ", fy[i][j]);//It's OK.
System.out.print(formatter.format("%.1f ", fy[i][j]));
}
System.out.println();
}
Formatter format(String format, Object... args)
Writes a formatted string to this object's destination using the specified format string and arguments.
Correct usage of Formatter:
Code:
import java.util.Formatter;
public class Fmt {
static public void main(String[] args) {
Formatter formatter = new Formatter(System.out);
int i = 0, j = 0;
float[][] fy = {{1.1f,2.1f,3.1f},
{2.7f,2.4f,6.3f},
{7.1f,8.1f,9f}};
for(i=0;i<3;i++) {
for( j=0;j<3;j++) {
//System.out.printf("%.1f ", fy[i][j]);//It's OK.
formatter.format("%.1f ", fy[i][j]);
}
System.out.println();
}
}
}
Thanks Snark1994 for your solution, it can work too.
But I still don't know why "Formatter.format" can't work in that way?
The short answer, as ntubski pointed out, is because "formatter" is a CLASS, not a "function".
It doesn't just "return a string" (although, superficially, it might look like it).
Rather, it ACTS ON a "string buffer". When you're done (possibly after multiple "format()" operations on your class object), then (and only then) you can call "toString()" on it and get your final, completely formatted string.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.