File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes printf question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "printf question" Watch "printf question" New topic
Author

printf question

Jeff Ciaccio
Greenhorn

Joined: Nov 26, 2008
Posts: 25
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!!


Jeff Ciaccio, Java novice <br />Physics and AP Physics Teacher<br />Sprayberry High School <br />Marietta, GA
Vladislav Mkrtychev
Greenhorn

Joined: Nov 29, 2008
Posts: 8
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

Joined: Oct 13, 2005
Posts: 40037
    
  28
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

Joined: Nov 26, 2008
Posts: 25
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

Joined: Oct 13, 2005
Posts: 40037
    
  28
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.
 
jQuery in Action, 2nd edition
 
subject: printf question