Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

printf question

 
Jeff Ciaccio
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can somebody please point me in the right direction. What is the proper syntax for printf when you have multiple strings and numbers? For example:


Thanks!!
 
Vladislav Mkrtychev
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I am kind of new to this as well, but the syntax is:

System.out.print(myVariable + "myString" + myDouble);
[ November 29, 2008: Message edited by: Vladislav Mkrtychev ]
 
Campbell Ritchie
Sheriff
Pie
Posts: 48954
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember printf only works in Java5 and higher. There are details in the Java� Tutorials and in the Formatter class.

I think what you want is

System.out.printf("The temperature is %.2fC or %.2fF.%n", celsius, fahrenheit);

That will print "The temperature is 20.00C or 68.00F.", assuming you haven't got a rounding error producing 67.99F or similar!
 
Jeff Ciaccio
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OH... so I don't need to specify strings at all. The % acts kind of like an escape character?

I had read the tutorial but did not see how to specify a string in addition to numbers. Your post was very helpful

Thanks Campbell!!
- jeff
 
Campbell Ritchie
Sheriff
Pie
Posts: 48954
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome. You can print a String variable with the %s tags. For entertainment purposes: try the %s tag with a variety of different Objects and see what happens. Then try the %b tag with a variety of different Objects and numbers and see what happens. Be sure to try some "null" references amongst the Objects.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic