Hello guys, I'm new in this forum and JAVA...
OK, here is the case. I want to build a Library Information System. I need to add BookSerialNumber (BSN). This BSN format goes like this : YYYY-CC-DDD. I'll explain it, YYYY = Year of the book published, CC = Category of the book, DDD = Digit count of the book according to Year and Category. Example : 2010-14-078. It's like lpad() function in SQL.
Example :(When I input...)
a) 78, the output 078
b) 4, the output 004
Is there any class or method or algoritm that I can use to make this text/String format?
Ok, that's my case. And I'm sorry if my English isn't so good. Thank's...
Yup, you can use String.format(...)
There's a format() method on String.
It takes the same format String as used by java.util.Formatter.
So reate a format string that matches the output you want (three parameters, one for year, one for category, one for count) and pass that and the various parameters into the format() method.
ETA: Bah! Serves me right for typing so much...
But very nice with all those shiny links :)
Originally Posted by Tolls
If you want "078" as an integer then you can use Integer.parseInt("078");
which will give you 78 as the output
He's going the other direction...from 78 to "078".
Hmm.. I'm sorry, I'm new to Java. Can you guys give a simple example code, please..?? Because I don't know how to use it...
It's like we have background string of 7 character '*******', so when I Input 'Word', the result is '***Word'. Or if I want the background string is '0000', so when I input '4', the result is '0004'.
Did you follow the links that Tolls has posted? What didn't you understand?
Can you make me an example code..?
System.out.println(String.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d"));
If your formatting is as simple as you show, you could use String concatenation and substring to get the output:
String output = ("00000" + "4").substring(2); ==> 0004
String output = ("00000" + "54").substring(3); ==> 0054
A bit of math will give you the substring arg to use based on leading chars, length of given string and length of desired results.
The formatter stuff, though, is handy to know as it's a standard (near as). I'd really recommend attempting it. It's all explained in those two links.
Thank's a lot guys. It's really helpful...
@Tolls I scanned the formatter doc and don't see how to format: ***WORD
A n(here 7) space result with a String right adjusted in it and *s(or any char) as filler.
I was looking for filler or default but didn't see it.
Just gone through it myself.
I could have sworn you could specify what character was used for the padding. Wonder what I'm thinking of then?