| 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: 32654
|
|
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: 32654
|
|
|
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.
|
 |
 |
|
|
subject: printf question
|
|
|