This is probably really simple, but I've been stuck on this for a while.
I am trying to output a String and then a double with two decimals followed by another string and here's is my code.
System.out.printf("Cost: %.2f%n" , hourCost , "/hour");
Gives output:
Cost: 8.00
What I would like to have:
Cost: 8.00/hour
I am not sure whether I can have two strings and a value between them when using printf.
Thanks in advance.
For your desired output, you need to add an additional format parameter. Change
System.out.printf("Cost: %.2f%n" , hourCost , "/hour");
to add a %s for the next String argument. Like,
System.out.printf("Cost: %.2f%s%n" , hourCost , "/hour");
There's no need to provide the second string as a separate argument unless it's a variable; in general, the other answers are correct, of course, but in your specific example you may use:
System.out.printf("Cost: %.2f/hour%n", hourCost);
Try using below code snippet
System.out.printf("Cost: %.2f%s" , hourCost , "/hour");
Related
I am new to C# having used Java.
I am looking to output an expression of 4.5 - 2.7... In Java I would simply write System.out.format("%.2f\n", 4.5 - 2.7);
In C#, I have used Console.WriteLine(4.5 - 2.7); but I am looking to print 2 decimal places.
Could someone be so kind as to explain how I achieve this?
Use String.Format (Link To Documentation)
Use the format {Parameter Number:Decimal Places}
Console.WriteLine(String.Format(" We are going to format 15.6345 as {0:0.00}",15.6345));
Test it here!.
Good luck!
EDIT / Clarification
By Parameter Number, String.Format takes all other inputs after the first input of a string to be values to format and place into the string.
Every time {x:yyz} appears in the string, System.String.Format will format x in the style yyz, where x is the index of the value passed in.
In my example above, 15.6345 is x, and the format 0.00 is yyz.
You could format 2 numbers or repeat one by going:
Console.WriteLine(String.Format(" We are going to format 15.6345 as {0:0.00} , the format 3.123 as 3.1 {1:0.0} , then repeat 15.6345 as 15.6 {0:0.0}",15.6345,3.123));
here is my code that isn't working:
Scanner hello = new Scanner (System.in);
double a = 10;
double c;
System.out.print("Enter the value: ");
c = hello.nextDouble();
double f = a + c;
System.out.printf("The sum of 10 plus user entry is : ", a+c);
No syntax error whatsoever, no error displayed, this is the result :
Enter the value: 100
The sum of 10 plus user entry is :
So there is no result in the second line,,, for the command ( a+c ) as in program. But if i use a ' %.2f ' before ( a+c ) command, it works fine,,
like :
System.out.printf("The sum of 10 plus user entry is : %.2f", a+c);
I tried to search about the '%.2f' but got to know it is used just to ascertain that the following number is to be displayed as a number with two decimal places. (kinda round off thing, i guess)..
I'm totally a rookie at Java. Started studying it at college right now. Was just curious to know about this concept and reason behind why this program worked only with the '%.2f' typed in it, and not without it, although it showed no error. Will be great if someone can answer it. thanks :-)
Java's System.out.printf() method doesn't append information; it substitutes it. The '%.2f' means: "Replace this with the next argument, and convert it to a floating-point number 2 places precise." Removing the '%.2f' would mean that a+c would have nowhere to go, and printf() would discard it.
Since Java's System.out.printf() method is actually based on the printf() from C/C++, you might want to check out this guide.
You are using the wrong function.
You should be using
System.out.println(myString)
Or
System.out.print(myString)
You would format your code as
System.out.println(myExplinationString + a+c)
System.out is an instance of java.io.PrintStream class that is provided as a static field of the System class. printf(String format, Object... args) is one of the methods of the PrintStream class, check this Oracle tutorial on formatting numbers. In brief, the first argument is a format string that may contain plain text and format specifiers, e.g. %.2f, that are applied to the next argument(s). All format specifiers are explained in the description of the java.util.Formatter class. Note, that double value is autoboxed to Double.
I am using a set of constant Strings for text anonymization. One of the strings should go something like "[Town in the state of XX]", where XX is to be replaced later with an actual state (the rest of the string remains as is).
My question is: is there a way to do this "elegantly" (in the spirit of a SQL PreparedStatement)?
Or should I just put XX and then do myString.replace("XX", "someState"), in which case, the string can no longer be a constant :(
EDIT: Just realized that String.replace returns a new String, so myString could still be a constant with this method.
If you use %s instead of XX, then you can simply use String.format.
You can use the Formatter class
And conveniently from system out
System.out.format("My name is '%s' and i am %d years old. My party will be at '%s'.", name, years, time);
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?
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.
System.out.println(whatever);
whatever can be a String, boolean, int, Point, whatever. Check out the docs.
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);
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.
At the end of my computations, I print results:
System.out.println("\nTree\t\tOdds of being by the sought author");
for (ParseTree pt : testTrees) {
conditionalProbs = reg.classify(pt.features());
System.out.printf("%s\t\t%f", pt.toString(), conditionalProbs[1]);
System.out.println();
}
This produces, for instance:
Tree Odds of being by the sought author
K and Burstner 0.000000
how is babby formed answer 0.005170
Mary is in heat 0.999988
Prelim 1.000000
Just putting two \t in there is sort of clumsy - the columns don't really line up. I'd rather have an output like this:
Tree Odds of being by the sought author
K and Burstner 0.000000
how is babby formed answer 0.005170
Mary is in heat 0.999988
Prelim 1.000000
(note: I'm having trouble making the SO text editor line up those columns perfectly, but hopefully you get the idea.)
Is there an easy way to do this, or must I write a method to try to figure it out based on the length of the string in the "Tree" column?
You're looking for field lengths. Try using this:
printf ("%-32s %f\n", pt.toString(), conditionalProbs[1])
The -32 tells you that the string should be left justified, but with a field length of 32 characters (adjust to your liking, I picked 32 as it is a multiple of 8, which is a normal tab stop on a terminal). Using the same on the header, but with %s instead of %f will make that one line up nicely too.
What you need is the amazing yet free format().
It works by letting you specify placeholders in a template string; it produces a combination of template and values as output.
Example:
System.out.format("%-25s %9.7f%n", "K and Burstner", 0.055170);
%s is a placeholder for Strings;
%25s means blank-pad any given String to 25 characters.
%-25s means left-justify the String in the field, i.e. pad to the right of the string.
%9.7f means output a floating-point number with 9 places in all and 7 to the right of the decimal.
%n is necessary to "do" a line termination, which is what you're otherwise missing when you go from System.out.println() to System.out.format().
Alternatively, you can use
String outputString = String.format("format-string", arg1, arg2...);
to create an output String, and then use
System.out.println(outputString);
as before to print it.
How about
System.out.printf("%-30s %f\n", pt.toString(), conditionalProbs[1]);
See the docs for more information on the Formatter mini-language.
http://java.sun.com/j2se/1.5.0/docs/api/java/text/MessageFormat.html
Using j-text-utils you may print to console a table like:
And it as simple as:
TextTable tt = new TextTable(columnNames, data);
tt.printTable();
The API also allows sorting and row numbering ...
Perhaps java.io.PrintStream's printf and/or format method is what you are looking for...