0

So, now I know that for integers I can use

 System.out.println("Name: %d", Name);

So, how do I print out other values in Java? Things like Strings, Boolean, Dates, and Doubles? Do I use %d for integers only?

prinsJoe
  • 683
  • 3
  • 7
  • 16
  • From http://stackoverflow.com/questions/3695230/how-to-use-java-string-format refer to docs at http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax – Elliott Frisch Nov 20 '13 at 03:53

4 Answers4

3

Regarding:

System.out.println("Name: %d", Name);

No, that won't work for println, for printf, yes, but not for println:

System.out.printf("Name: %d", Name);

or if you want a new line:

System.out.printf("Name: %d%n", Name);

For booleans, %b, for doubles, %f, for Strings %s .... Dates would require a combination of specifiers (or I would just use a SimpleDateFormat object myself). Note that these specifiers can take width constants to give them more power at formatting the output. e.g.,

System.out.printf("Pi to four places is: %.4f%n", Math.PI);

Please check the Formatter API for more of the details.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0
System.out.println(whatever);

whatever can be a String, boolean, int, Point, whatever. Check out the docs.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

Anything you put inside the parenthesis of System.out.println() or System.out.print() is formatted and printed as a string. However, you can control how variables are printed out inside your string (as you did using %d) using Java's printf() method.

The printf() method takes two parameters: the string to print and a list of variable names. You insert the format flags (%d, %f, etc) in the string and you list the variables you want formatted in the string second.

System.out.printf("Your total is %d", 29.99);

This means that Java will format 29.99 as a decimal rather than a string when it outputs "Your total is 29.99".

You can check out the other types of formatting in the "conversion type character" table here.

user2121620
  • 678
  • 12
  • 28
0

You can do System.out.println("something"); if you want to skip a line after printing, but if you want to print something, then continue on the same line, then you should just do System.out.print("something"); You can also just print out Strings, boolean values (t/f) and doubles just by doing something like
System.out.println(booleanname); or
System.out.println(Stringname; or
System.out.println(doublevariablename);