Question:
Print a string and a variable all in the same print statement (java)?
anonymous
2014-06-10 16:01:19 UTC
Instead of having to print two lines, can I just print a variable and a string of text all within a single print statement?

So instead of

System.out.print("The answer is: $");
System.out.print(answer);


Can I do something like this?


System.out.print("The answer is: $", answer);
Four answers:
?
2014-06-10 16:14:16 UTC
Yes, you can, but you should use the + operator, not a comma.



System.out.println("The answer is: $" + answer);



Assuming answer has a toString() method defined if it's an object (all strings do) or a primitive type (int, double, float, char, etc...)
anonymous
2014-06-10 16:05:17 UTC
yes
John
2014-06-11 03:32:13 UTC
some of them are listed



double answer = 1234.55;

System.out.println("The answer is: $" + answer);

System.out.format("The answer is: $%,.2f%n", answer);

System.out.printf("The answer is: $%,.2f%n", answer);

System.out.println("The answer is: $" + String.format("%,.2f", answer));
?
2014-06-10 16:45:39 UTC
System.out.println () does not give you fine control over the format of the printed text. A new addition to the fold is System.out.printf (....); (Note the final f after print).



A call to this method looks like this:



System.out.printf ("format string", a1, a2, a3, ..etc..);



Inside the format string you can mix text and special format markers. For example, the format marker %d prints a number in decimal. You can specify (say) 2 digits after the decimal point like this: %d.2



Now you can say:



System.out.printf ("The answer is : $%d.2", answer);


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...