This question already has answers here:
Is there a good reason to use "printf" instead of "print" in java?
(4 answers)
Closed 9 years ago.
When is it considered good code to format a string output like this:
int count = 5;
double amount = 45.6;
System.out.printf("The count is %d and the amount is %45.6", count, amount);
utilising a printf statement, over code like this:
int count = 5;
double amount = 45.6;
System.out.print("The count is " + count + "and the amount is " + amount);
using a print statement?
I have read the JavaDocs which state that printf is "A convenience method to write a formatted string to this output stream using the specified format string and arguments."
But it doesn't state when, by convention, we should use one over the other?
So, when is it good coding to use a printf, and when is it good coding not to?
Thanks for any help.
Two methods are provided for the convenience of a coder and for different needs. If you need string formatting then go for printf method but if there is no formatting required simply use print method and void %d,%s, etc formatters.
If you want to control the precision & padding of floating point numbers then use printf otherwise go for print.
printf was added quite recently in the history of java as a convenience because so many people were used to C style printf and what it could do. so one isnt really better or preferred over the other. Regular "print" style though is clearer and simpler when special printf formatting isnt required.
Related
This question already has answers here:
Java BigDecimal can have comma instead dot?
(3 answers)
Closed 3 months ago.
I have a method to set a BigDecimal number that is given as String:
private Client mapClient(Client client){
ClientRequest clientRequest = new ClientRequest();
// Code
clientRequest.setCashAmount(castStringToBigDecimal(client.getCashAmount()));
// More Code
}
My castStringToBigDecimal method is the follosing:
public BigDecimal castStringToBigDecimal(String value){
BigDecimal response = null;
if(value != null && !value.equals("")){
value = value.replaceAll("[.]", ",");
response = new BigDecimal(value);
}
return response;
}
An example of the input value is "1554.21"
I need that the bigDecimal separator to be a comma, not a dot. But this is giving me an exception.
EDIT
The value is the following:
And the exception is:
java.lang.NumberFormatException: Character , is neither a decimal digit number, decimal point, nor "e" notation exponential mark.
BigDecimal doesn't represent a rendering. In other words, whether to use a comma or a dot as separator is not part of the properties a BigDecimal object has.
Hence, you do not want to call .replaceAll. (And separately, you'd want .replace(".", ",") - replace replaces all, and replaceAll also replaces all and interprets the first arg as a regex, and is therefore needlessly confusing here). Just pass it with the dot.
To render a BigDecimal, don't just sysout it, that will always show a dot and there is nothing you can do about that. toString() is almost never the appropriate tool for the job of rendering data to a user - it's a debugging aid, nothing more. Use e.g. String.format("%f"), specifying the appropriate locale. Or use NumberFormat. The javadoc of BigDecimal explicitly spells this out.
There are various other issues with your code:
"cast" is the technical name for the syntactic construct: (Type) expr; - and this construct does 3 utterly different things, hence using it to describe a task, i.e. use it in a method name, is a very bad idea. In particular, only one of the 3 things it does converts anything, and you clearly use it here in the 'convert something' meaning. This is misleading; only if it's all primitives does the cast operator convert, and BigDecimal isn't primitive. Call it convertTo or whatever you please, not "cast".
BigDecimal is an extremely complicated tool for the job and usually not the right tool if you want to represent financial data. Instead, represent the atomary unit in a long and call the appropriate rendering method whenever you need to show it to a user. For example, for euros, the atomary unit is the eurocent. If something costs €1,50, you'd store "150", in a long. Before you think: But, wait, I want to divide, and then I'd lose half a cent! - yes, well, you can't exactly send your bank a request to transfer half a cent, either. Also, try to divide 4 cents by 3 with a BigDecimal and see what happens. Dividing financial amounts is tricky no matter what you use, BD isn't a catch-all solution to this problem.
I looked up the source code for Java 8's implementation of BigDecimal (https://github.com/frohoff/jdk8u-dev-jdk/blob/master/src/share/classes/java/math/BigDecimal.java), and the period character is hard-coded in that source as the decimal point. I would not have thought this of a language for which internationalization has been so thoroughly designed in, but there it is, line 466.
Given that the author(s) of BigDecimal failed to take locale into account in such a basic way -- the use of comma instead of period as the decimal separator in Europe is well-known -- I'd have to say you cannot use that BigDecimal constructor on unaltered Strings that are otherwise formatted correctly but which (might) have a comma separator. There are other options -- the previous SO post referred to in one of the comments has one -- but it appears you cannot convert your String this way.
(One minor point -- you are not "casting" anything. That word has a specific meaning in OO programming, and a more specific one in Java, and has very little to do with your question. It is incorrect to refer to conversion as casting.)
This question already has answers here:
Java output formatting for Strings
(6 answers)
Closed 11 months ago.
Given these variables:
int a = 1, b = 123, c = 55, d= 1231;
Is there a way in Java to print them with a set width of 5, say. In case number is less than five digits - only print dashes.
1----,123--,55---,1231-
I am aware that these can be achieved with some loops and if statements, looking for something similar to setw() from C++
System.out.println(String.format("%-5.5s", s).replace(" ", "-"));
In short, you can't do it directly. Java has functionality broadly similar to that of C's "printf" formatting.
You can set a field width, you can justify left or right, but your fill characters are limited to zero and space.
Documentation
If the format uses the general "%s" directive, and the corresponding argument is of a class under your control, then you can implement a 'formatTo' method to do the conversion. So a wrapper class might be useful to you.
This question already has answers here:
How do I format a number in Java?
(9 answers)
Closed 5 years ago.
How do I format a string with commas to display in curreny format?
Assume the incoming string is a big number. For example:
"1234567901234567890123456"
I want result as:
"12,345,678,901,234,567,890,123,456"
The DecimalFormat in Java has a limitation to format a big number.
95% of problems are solved by clarifying your requirements. Let's filter out the things that are definitely not requirements. "incoming string is a big number" - that statement can never hold true. Is it a String? If yes, then it's a String, and never a number. This distinction is important. I'll assume that the answer to this question is "yes".
Now that you have a String, why are you using a DecimalFormat? What does a String have to do with a decimal number formatter? Nothing related to the problem that you are trying to solve. I'll leave the determination of the correct approach to solve your problem up to you - after all, my speculations at your requirements may not be correct.
To reiterate, here are the things that are definitely incorrect:
- You have a String, that is a big number"
- DecimalFormat has an issue with "big numbers" - an unsubstantiated conclusion drawn on a false basis of understanding.
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(35634646));
Output: 35,634,646
This would do
double formatThis = Double.parseDouble(yourNumber);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(formatThis));
You should be able to achieve the desired using the expression posted below:
(?n:(^\$?(?!0,?\d)\d{1,3}(?=(?<1>,)|(?<1>))(\k<1>\d{3})*(\.\d\d)?)$)
Try this.
String input = "12345678901234567890123456";
String output = String.format("%,d", new BigInteger(input));
System.out.println(output);
// -> 12,345,678,901,234,567,890,123,456
For a programming project in Calculus we were instructed to code a program that models the Simpson's 1/3 and 3/8 rule.
We are supposed to take in a polynomial(i.e. 5x^2+7x+10) but I am struggling conceptualizing this. I have began by using scanner but is there a better way to correctly read the polynomial?
Any examples or reference materials will be greatly appreciated.
I'd suggest that you start with a Function interface that takes in a number of input values and returns an output value:
public interface Function {
double evaluate(double x);
}
Write a polynomial implementation:
public class Poly {
public static double evaluate(double x, double [] coeffs) {
double value = 0.0;
if (coeffs != null) {
// Use Horner's method to evaluate.
for (int i = coeffs.length-1; i >= 0; --i) {
value = coeffs[i] + (x*value);
}
}
return value;
}
}
Pass that to your integrator and let it do its thing.
A simple way (to get you started) is to use an array.
In your example: 5x^2 + 7x + 10 would be:
{10,7,5}
I.e. at index 0 is the factor 10 for x^0 at index 1 is 7 for x^1 at index 2 is 10 for x^2.
Of course this not the best approach. To figure out way figure out how you would represent x^20
In java it would be easiest to pre-format your input and just ask for constants--as in, "Please enter the X^2 term" (and then the X term, and then the constant).
If that's not acceptable, you are going to be quite vulnerable to input style differences. You can separate the terms by String.split[ting] on + and -, that will leave you something like:
[5x^2], [7x], [10]
You could then search for strings containing "x^2" and "x" to differentiate your terms
Remove spaces and .toLowerCase() first to counter user variances, of course.
When you split your string you will need to identify the - cases so you can negate those constants.
You could do two splits, one on + the other on -. You could also use StringTokenizer with the option to keep the "Tokens" which might be more straight-forward but StringTokenizer makes some people a little uncomfortable, so go with whatever works for you.
Note that this will succeed even if the user types "5x^2 + 10 + 7 x", which can be handy.
I believe parsing is my problem. I am somewhat new to java so this is troubling me.
You should use a parser generator.
A parser generator is a tool that reads a grammar specification and converts it to a Java program that can recognize matches to the grammar. In addition to the parser generator itself, JavaCC provides other standard capabilities related to parser generation such as tree building (via a tool called JJTree included with JavaCC), actions, debugging, etc.
JavaCC's FAQ answers How do I parse arithmetic expressions?
See the examples that come with JavaCC.
See any text on compiling.
See Parsing Epressions by Recursive Descent and a tutorial by Theodore Norvell.
Also, see JavaCC - Parse math expressions into a class structure
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java printf using variable field size?
I haven't worked with Java in a while so I was looking for a way to
specify variable width in format/printf when formatting/printing output. My example shows the use with an integer, but of course I'd like this to work for other types too.
E.g., something along the lines of
int val = 8;
int wid = 5;
System.out.printf("%"*d\n", wid, val);
I could use this work-around, which is ugly:
System.out.printf("%"+wid+"d\n", val);
Was the * variable field width specifier removed from Java? This old'ish
page, section 1.3.1,
shows the use (like it would be used in C), but I can't get it to
work, resulting in:
java.util.UnknownFormatConversionException: Conversion = '*'
nor have I been able to find more recent references that this
does work.
Is there an easier way to do this other than my work-around above?
I did look around before posting and came across this about 2-year old SO question Java printf using variable field size? but is that the final word on this?
The general syntax of a format specifier is
%[parameter][flags][width][.precision][length]type
Instead of printf, you can also use
String.format("%"+wid+"d",val);
And yes, these are the only ways in case you are using a Java Formatter.