| Formatting a string in Java |
|
 |
Index ‹ java-programmer
|
- Previous
- 1
- I really need help with this so if anyone can help me out that would be really great of you.On Feb 6, 9:12 pm, Lew <email***@***.com> wrote:
> email***@***.com wrote:
> >> Part II
>
> >> To make a profit a local store marks up the prices of its items by
> >> 25%. Write a Java program that declares the following variables:
> >> 1. a double variable named percent_markedup
> >> 2. a double variable named original_price
> >> 3. a double variable named sales_tax_rate
>
> >> In your program be sure to assign a value to each of the variables 1-3
> >> above. Use initialization for 1 and 2 and for 3.
>
> >> Using the information from above, the program should then output:
> >> 1. the original price of the item
> >> 2. the marked-up percentage of the item (original price times percent
> >> of markup)
> >> 3. the store's selling price of the item
> >> 4. the sales tax rate
> >> 5. the sales tax
> >> 6. the final price of the item (the final price of the item is the
> >> selling price plus the sales tax)
>
> >> can u send me an email or using this to communicate.
>
> Please do not use textspeak in Usenet posts.
>
> A couple of points about your assignment that you will need to know if you
> ever use Java outside of school:
>
> - by long-standing and nearly rigid convention, Java variables are spelled
> without underscores and with mixed case, capitalizing each word part except
> the first, hence "percentMarkedUp".
>
> - doubles work fine as currency values for academic work, but not so much in
> the real world. The issues are somewhat complex, so we stick with doubles
> until we've learned some more of the basics.
>
> Let's review your assignment piece by piece:
>
> >> Write a Java program
>
> I'll give you this part. A "Java program" is a class with a properly-defined
> main() method.
>
> package programming.oneohone;
> public class RetailModel
> {
> public void main( String [] args )
> {
> }
>
> }
> >> that declares the following variables
>
> There are two places you could declare variables so far, within the class
> itself as instance or class variables, or within the main() method. The
> main() method is simpler, so start there.
>
> >> 1. a double variable named percent_markedup
> >> 2. a double variable named original_price
> >> 3. a double variable named sales_tax_rate
>
> Do you know how to declare variables? I'll give you one, focusing in on just
> the main() method and not the rest of the class.
>
> public void main( String [] args )
> {
> double percent_markedup;
> }
>
> It's the same for the others.
>
> >> In your program be sure to assign a value to each of the variables 1-3
> >> above. Use initialization for 1 and 2 and for 3.
>
> Well, the declaration of 1. that I showed you doesn't assign a value, because
> it doesn't have an initialization clause.
>
> Yet.
>
> The tutorial gives a hint near the top of the page about initialization, in
> case you forget the course information:
> <http://java.sun.com/docs/books/tutorial/java/nutsandbolts/variables.html>
>
> So go ahead and modify the declarations you just wrote and add the
> initializations.
>
> Solve one itty-bitty problem at a time, and make sure your program is correct
> at each stage. Only then add in the next piece of the puzzle, one itty-bitty
> problem at a time.
>
> This is beginning to sound a lot like Patricia Shanahan's advice, isn't it?
> You should go back to her link and read it again, very carefully.
>
> Quiz: Where (in what file) do you store the source code for your RetailModel
> program?
>
> General advice: Read the rest of the tutorial, not just the one page I linked
> you to.
>
> --
> Lew
hey Lew thank you soo soo much that instruction by instruction really
helped me a lot and thank you so much again.
- 1
- Clipboard doesn't see changes to the system-clipboard...I have an signed Applet with a JTable, where I have implemented
"cut & paste" to/from the system clipboard.
(The applet is signed to get access to the system clipboard).
Everything works as expected; Copying a row from ie. Excel,
and pasting it into a JTable row, or the other way around.
But... After I do a "local" copy/paste, that is, copy a row from
my JTable, and pasting it into another row, the Applet doesn't see
changes to the system-clipboard anymore. If I after this copy a new
row out of Excel, and try to paste it into my Applet table, what I get
is the old data from my last "local" copy-paste operation.
Anyone seen this behaviour before?
Any hints?
TIA...
- 2
- create a new windows (xp) service that runs a jar fileHello guys,
Does anyone has experience/know how to create a new windows (xp)
service that runs a jar file? This issue rises as i need to hide the
most of the java implementation in this project before it goes live.
So the idea is, to have control on the exceution of the jar from
windows windows service console (which the users can define the startup
type i.e. manual, automatic, disabled and the running life cycle i.e.
start, stop, pause, resume, restart...).
so any leads to solving this will be appreciated.
Thanks in advance. Have a nice day!
- 3
- JSP codeHi,
I have the following code
<html>
<head>
<title>
Authentication
</title>
</head>
<body>
<%!
private String username = null;
private String password = null;
private boolean completeLoginInformation=true;
%>
<%
username = request.getParameter("username");
password = request.getParameter("password");
%>
<H2><p>Checking authentication...</p></H2>
<%
if (username == null)
{ completeLoginInformation = false;
%><p><H3>Username has been left empty...</H3></p>
<% } %>
<%
if (password == null)
{ completeLoginInformation = false;
%><p><H3>Password has been left empty...</H3></p>
<% } %>
<% if (completeLoginInformation == false) { %>
<p><a href="http://localhost:8080/jsp-examples/cal/Front.jsp">Return
back to Front Page</a></p>
<p><a href="http://localhost:8080/jsp-examples/cal/AdminLog.jsp">Return
back to Administration Authentication</a></p>
<% } else { %>
<p>Need to search in database</p>
<p>All data has been entered</p>
<% } %>
</body>
</html>
Now when username and password arguments are given as empty, the flag
is supposed to be set free and in the web browser shows me the 2 links
given. Instead, the else part is being given.
Can someone help me out
Thanks in Advance
- 3
- StreamCorruptedExceptionHi
sorry my english is not very good [:())
i have something like that:
Socket------------------------------------------------class1------ObjectOutp
utStream
|
|
|
inner class in class1-thread-ObjectInputSt.
|
-----------------class2
| |
| inner class in class2 thread ObjectInputStream,
ObjectOutputStream
|
|
|
--------class3- and here when i create ObjectOutputStream in inner class in
class1 in thread
jumps out exception StreamCorruptedException
why?
please help
i don't know what i have should do?
Czeski
- 3
- What Collection to use?Dear all,
My app can load files using a FileChooser. I would like to store the
last 4 loaded file pathes so I can use them later (ie fast access to
last used files). I'm looking for the perfect Collection to store these
4 File objects.
I think it should have the following properties
1. no duplicate objects
2. knowing the insert order (so you know which was last entered)
3. limited size (4 objects) and throwing out the oldest entry when
inserting a new one (like a ring buffer maybe)
Is there such a Collection already or do I have to homecook one?
Thanks for your answers
Phil
PS: Is there a summary table on the web with all properties of the
standard subclasses of Collection and Map?
- 4
- instanceOf operator new bie questionI am using Java 1.4.2.x
I wrote following code:
NumberFormat df;
df = NumberFormat.getInstance();
if (df instanceof DecimalFormat) {
((DecimalFormat) df).setMinimumIntegerDigits(1);
((DecimalFormat) df).setDecimalSeparatorAlwaysShown(true);
}
What does "df instanceof DecimalFormat" really mean? Does it mean that
NumberFormat can be converted to DecimalFormat? Because my
NumberFormat.getInstance() is returning me a NumberFormat and not
DecimalFormat what else could it mean.
I did read about instanceOf opeartor on google, but it is still
confusing to me.
Thanks a lot.
Prem
- 4
- do XML/XSD validation with Ant 1.5.4 and JDK 1.4.2. How?Buried somewhere in the documentation for the 1.4 JDK is a statement that
the included XML parser class cannot do schema validation (DTD validation:
yes, Schema validation: no). However, I believe that Ant uses the XML
parser in its ANT_HOME/lib directory. You probably have an older xerxes.jar
and the your best bet is to delete that and download the latest xerces.jar
and drop it into the ANT_HOME/lib directory.
<email***@***.com> wrote in message
news:email***@***.com...
> I really need to be able to validate XML against an XSD, using Ant
> 1.5.4 and JDK 1.4.2. It appears this is straightforward to do with the
> latest Ant release and/or the latest JDK, but not with the releases
> that I'm limited to.
>
> I noticed the "iso-relax" sourceforge project, which includes the JARV
> library (which contains the Ant task). This was promising, but it
> causes an NPE to be thrown in Xerces' XMLSchemaValidator class, and I
> have no idea why.
>
> I'm querying the ant-user mlist about this, but I figured this would be
> another good place to try.
>
- 5
- JTabel and JScrollPane doens't scrollHello,
I have a problem with a larger table.
I have a JTable whiches model contains 38 columns.
I put this Table in a JScrollPane. But on the screen there is no
scrollbar but a table with 38 very small columns.
I thought there must be a scroll bar for horizontal scrolling instead.
Are there any traps in this?
kind regards
Falko
- 5
- Exec() Help!Hi,
I'm trying to start an external applet from an applet I'm writing. I know
Exec() Is the key, but I don't know how to use it. I know how to execute
external native programs (I.e. programs I have written in BASIC and
compiled). But starting an applet from an applet totally throws me. I have
tried searching the net, and that has a lot to say about executing shell
scripts, and natives - which I know how to do.
What classes do I need to import? what line of code invokes an external
applet? I don't need to grab output from the applet I want to execute, or
send input. I just want it to run.
Pleeeeeeez can anyone help, my project has to be handed in soon :-(
Thanks,
Dafydd.
- 7
- Convert from text string "Hello" to floating-point number issueHi there,
My java lecturer has given us an assignment related to casting and
type conversion etc.
One of the conversions he wan't is convert "Hello" to a float.
I suspect this is a trick question on his part as "Hello" is not a
parsible value.
This is the code I have:
//Convert String object "s" to a Float object
//then convert Float object to float value
try { System.out.println("String is "+s+" float is
"+Float.valueOf(s).floatValue());
}
catch (NumberFormatException NFE)
{ System.out.println("NumberFormatException: "+ NFE.getMessage()+
" The input string does not contain a parsable number"); }
I emailed the guy but he says just to use your own judgement.
I looked at the API for the wrapper classes etc and I think a
conversion of this type is almost impossible.
Any ideas welcome.
- 12
- Problems in printing an IntegerHamvil ha scritto:
> 1) why I get the blank page instead of the usual exception in the jsp
> page?
Ok, I've fixed this (it was a problem with the configuration of the
logger
> 2) why the variable cannot be printed?
In the logger i get the following message:
javax.servlet.jsp.JspException: Cannot find message resources under key
org.apache.struts.action.MESSAGE
What I do not understand is why struts looks for a key in the resources
file. It should just print the integer. Am I missing somethink?
BTW if I add the following in the struts-config the problem look fixed.
Is this the right approach?
<message-resources
parameter="MyWebAppResources"
null="false" />
Thanks
- 12
- JDK1.5 with JbossGreetings,
I want to try and work with some EJB3 stuff for a small website hosted on a
FreeBSD 5.4 server and was wondering at the state of JDK1.5 port and if it
is ok to use it with Jboss under FreeBSD.
Thanks
John
- 12
- Java In A Nutshell, 5th Edition moreWith more than 700,000 copies sold to date, Java in a Nutshell from
O'Reilly is clearly the favorite resource amongst the legion of
developers and programmers using Java technology. And now, with the
release of the 5.0 version of Java, O'Reilly has given the book that
defined the "in a Nutshell" category another impressive tune-up.
In this latest revision, readers will find Java in a Nutshell, 5th
Edition does more than just cover the extensive changes implicit in
5.0, the newest version of Java. It's undergone a complete makeover--in
scope, size, and type of coverage--in order to more closely meet the
needs of the modern Java programmer.
more http://www.cdbook.cn/book.asp?id=676
- 13
- Job for the Position of Project Lead in a MNC at BangaloreCompany Profile :
The company is an ISO 9001:2000 Quality certified company, is in the
business of providing world-class software solutions and support
services to its clients. Located in Bangalore. They provide IT
services across various domains such as Insurance, Financial Services,
Travel, Retail, and Logistics etc. They have been building customized
applications that have robust layers of application architecture.
Job Profile :
Incumbent should have hands on in Core Java, MVC Architecture, Design
Patterns,J2EE, Struts,EJB, MySQL
Must have knowledge of APEX.
Should have min 6 yrs of exp
Should have good oral and written communication and good analytical
skills
Job location: Bangalore
Salary wont be a constraint for the right candidate.
If you are interested..send me your updated resume as soon as
possible email***@***.com
|
| Author |
Message |
Jerry Manner

|
Posted: 2007-9-28 17:28:00 |
Top |
java-programmer, Formatting a string in Java
Hi
I am a newby in Java and am trying to format a string into a fixed
number of positions( in this case 5).
So if I have a "5" in should be "00005", and "23" should be "00023".
I hav tried looking at the classes 'import java.text.NumberFormat' and
'import java.text.Format', but I didn't get far.
Can anyone help me how I can do this in java?
Any help will be appreciated.
Regards
|
| |
|
| |
 |
Jean-Baptiste Nizet

|
Posted: 2007-9-28 18:28:00 |
Top |
java-programmer >> Formatting a string in Java
On 28 sep, 11:28, Jerry Manner <email***@***.com> wrote:
> Hi
>
> I am a newby in Java and am trying to format a string into a fixed
> number of positions( in this case 5).
> So if I have a "5" in should be "00005", and "23" should be "00023".
>
> I hav tried looking at the classes 'import java.text.NumberFormat' and
> 'import java.text.Format', but I didn't get far.
>
> Can anyone help me how I can do this in java?
>
If the string you want to format always represents a positive integer,
you might use a DecimalFormat:
NumberFormat format = new DecimalFormat("00000");
System.out.println(format.format(Integer.parseInt("23")));
System.out.println(format.format(Integer.parseInt("5")));
Else, the following code snippet works as well. Pretty basic
programming:
private static String format(String s) {
int length = s.length();
if (length >= 5) {
return s;
}
else {
StringBuffer buffer = new StringBuffer(5);
for (int i = length; i < 5; i++) {
buffer.append('0');
}
buffer.append(s);
return buffer.toString();
}
}
JB.
|
| |
|
| |
 |
Lionel van den Berg

|
Posted: 2007-9-28 19:02:00 |
Top |
java-programmer >> Formatting a string in Java
Jean-Baptiste Nizet wrote:
> On 28 sep, 11:28, Jerry Manner <email***@***.com> wrote:
>> Hi
>>
>> I am a newby in Java and am trying to format a string into a fixed
>> number of positions( in this case 5).
>> So if I have a "5" in should be "00005", and "23" should be "00023".
>>
>> I hav tried looking at the classes 'import java.text.NumberFormat' and
>> 'import java.text.Format', but I didn't get far.
>>
>> Can anyone help me how I can do this in java?
>>
>
> If the string you want to format always represents a positive integer,
> you might use a DecimalFormat:
>
> NumberFormat format = new DecimalFormat("00000");
> System.out.println(format.format(Integer.parseInt("23")));
> System.out.println(format.format(Integer.parseInt("5")));
>
> Else, the following code snippet works as well. Pretty basic
> programming:
>
> private static String format(String s) {
> int length = s.length();
> if (length >= 5) {
> return s;
> }
> else {
> StringBuffer buffer = new StringBuffer(5);
> for (int i = length; i < 5; i++) {
> buffer.append('0');
> }
> buffer.append(s);
> return buffer.toString();
> }
> }
That seems longer than necessary, why not:
private static String format(String s) {
String formattedString = s;
while(formattedString.length() < 5) {
formattedString = "0" + formattedString;
}
return formattedString;
}
You could provide length as a parameter too.
Lionel.
P.S. in your example I think you wanted to prepend to buffer?
Lionel.
|
| |
|
| |
 |
Jerry Manner

|
Posted: 2007-9-28 19:03:00 |
Top |
java-programmer >> Formatting a string in Java
On 28 sep, 12:27, Jean-Baptiste Nizet <email***@***.com> wrote:
> On 28 sep, 11:28, Jerry Manner <email***@***.com> wrote:
>
> > Hi
>
> > I am a newby in Java and am trying to format a string into a fixed
> > number of positions( in this case 5).
> > So if I have a "5" in should be "00005", and "23" should be "00023".
>
> > I hav tried looking at the classes 'import java.text.NumberFormat' and
> > 'import java.text.Format', but I didn't get far.
>
> > Can anyone help me how I can do this in java?
>
> If the string you want to format always represents a positive integer,
> you might use a DecimalFormat:
>
> NumberFormat format = new DecimalFormat("00000");
> System.out.println(format.format(Integer.parseInt("23")));
> System.out.println(format.format(Integer.parseInt("5")));
>
> Else, the following code snippet works as well. Pretty basic
> programming:
>
> private static String format(String s) {
> int length = s.length();
> if (length >= 5) {
> return s;
> }
> else {
> StringBuffer buffer = new StringBuffer(5);
> for (int i = length; i < 5; i++) {
> buffer.append('0');
> }
> buffer.append(s);
> return buffer.toString();
> }
> }
>
> JB.
Hi
Thank you very much. Your tip helped me alot. Up to the next challenge
for me :-)
Kind Regards
|
| |
|
| |
 |
J黵gen Gerstacker

|
Posted: 2007-9-28 19:07:00 |
Top |
java-programmer >> Formatting a string in Java
Why not
String.format("%05d", 5);
String.format("%05d", 23);
?
Juergen
|
| |
|
| |
 |
Jean-Baptiste Nizet

|
Posted: 2007-9-28 19:50:00 |
Top |
java-programmer >> Formatting a string in Java
On 28 sep, 13:01, Lionel van den Berg <email***@***.com> wrote:
>
>
> That seems longer than necessary, why not:
>
> private static String format(String s) {
> String formattedString = s;
>
> while(formattedString.length() < 5) {
> formattedString = "0" + formattedString;
> }
> return formattedString;
>
> }
>
Because concatenating strings in a loop is very bad practice. It's one
of the main reasons of the existence of the StringBuffer class (I
should have used a StringBuilder, in fact, which is even more
performant).
Indeed, your code after compilation is equivalent, AFAIR, to the
following:
while (formattedString.length() < 5) {
StringBuffer tmp = new StringBuffer();
tmp.append("0");
tmp.append(formattedString);
formattedString = tmp.toString();
}
You see that lots of StringBuffer and String instances are created,
which makes the performance of such code terrible.
Moreover, my code also avoids calling the String length method at each
iteration.
JB.
|
| |
|
| |
 |
Lew

|
Posted: 2007-9-28 19:51:00 |
Top |
java-programmer >> Formatting a string in Java
Lionel van den Berg wrote:
> private static String format(String s) {
> String formattedString = s;
>
> while(formattedString.length() < 5) {
> formattedString = "0" + formattedString;
This type of thing is often a frequently-traversed code path, making it a
prime candidate to use StringBuilder to avoid all those messy intermediate
String objects.
> }
> return formattedString;
> }
--
Lew
|
| |
|
| |
 |
Jean-Baptiste Nizet

|
Posted: 2007-9-28 19:53:00 |
Top |
java-programmer >> Formatting a string in Java
On 28 sep, 13:06, J黵gen Gerstacker <email***@***.com> wrote:
> Why not
>
> String.format("%05d", 5);
> String.format("%05d", 23);
>
Because the OP wants to format Strings, and not integers. But thanks
to remind me that the String.format method exists. Since I learnt Java
a long long time ago and this method didn't exist at the time, I've
not taken the habit to use it.
JB.
|
| |
|
| |
 |
Lew

|
Posted: 2007-9-28 19:59:00 |
Top |
java-programmer >> Formatting a string in Java
Jean-Baptiste Nizet wrote:
> while (formattedString.length() < 5) {
> StringBuffer tmp = new StringBuffer();
> tmp.append("0");
> tmp.append(formattedString);
> formattedString = tmp.toString();
> }
Sigh.
> You see that lots of StringBuffer and String instances are created,
> which makes the performance of such code terrible.
Nothing wrong with creating lots of StringBuffers except that you should've
used StringBuilder.
Here's a better loop:
int len = formatted.length();
// why put "String" in the name of a String?
StringBuilder sb = new StringBuilder( "" );
while ( len++ < 5 )
{
sb.append( '0' );
}
formatted = sb.append( formatted ).toString();
You can wrap the whole loop and reassignment in an
if ( len < 5 )
to short-circuit unnecessary reassignment of "formatted".
--
Lew
|
| |
|
| |
 |
Lew

|
Posted: 2007-9-28 20:00:00 |
Top |
java-programmer >> Formatting a string in Java
Lew wrote:
> StringBuilder sb = new StringBuilder( "" );
equivalent to
StringBuilder sb = new StringBuilder();
but I wanted to make the intent here crystal clear.
--
Lew
|
| |
|
| |
 |
Jean-Baptiste Nizet

|
Posted: 2007-9-28 20:25:00 |
Top |
java-programmer >> Formatting a string in Java
On 28 sep, 13:59, Lew <email***@***.com> wrote:
> Jean-Baptiste Nizet wrote:
> > while (formattedString.length() < 5) {
> > StringBuffer tmp = new StringBuffer();
> > tmp.append("0");
> > tmp.append(formattedString);
> > formattedString = tmp.toString();
> > }
>
> Sigh.
>
> > You see that lots of StringBuffer and String instances are created,
> > which makes the performance of such code terrible.
>
> Nothing wrong with creating lots of StringBuffers except that you should've
> used StringBuilder.
>
> Here's a better loop:
>
> int len = formatted.length();
> // why put "String" in the name of a String?
> StringBuilder sb = new StringBuilder( "" );
> while ( len++ < 5 )
> {
> sb.append( '0' );}
>
> formatted = sb.append( formatted ).toString();
>
> You can wrap the whole loop and reassignment in an
> if ( len < 5 )
> to short-circuit unnecessary reassignment of "formatted".
>
Sigh.
You should re-read my first post in this thread, then the reply from
Lionel van den Berg, and my reply to his reply, to which you have just
answered with a "Sigh".
The text, in English, before and after the code snippets, is part of
the post, and you should read it as well. The code snippet was
precisely there to explain to Lionel why he must not concatenate
Strings inside loops, since doing it results in the same bytecode as
the ugly loop above, with lots of StringBuffer and String creations.
JB.
|
| |
|
| |
 |
Lionel van den Berg

|
Posted: 2007-9-29 6:24:00 |
Top |
java-programmer >> Formatting a string in Java
Jean-Baptiste Nizet wrote:
> On 28 sep, 13:01, Lionel van den Berg <email***@***.com> wrote:
>>
>> That seems longer than necessary, why not:
>>
>> private static String format(String s) {
>> String formattedString = s;
>>
>> while(formattedString.length() < 5) {
>> formattedString = "0" + formattedString;
>> }
>> return formattedString;
>>
>> }
>>
>
> Because concatenating strings in a loop is very bad practice. It's one
> of the main reasons of the existence of the StringBuffer class (I
> should have used a StringBuilder, in fact, which is even more
> performant).
> Indeed, your code after compilation is equivalent, AFAIR, to the
> following:
>
> while (formattedString.length() < 5) {
> StringBuffer tmp = new StringBuffer();
> tmp.append("0");
> tmp.append(formattedString);
> formattedString = tmp.toString();
> }
>
> You see that lots of StringBuffer and String instances are created,
> which makes the performance of such code terrible.
I wise man told me, write neat code first and don't worry about
performance. If performance becomes a problem then go back an worry
about it.
I will stick to my neat version, but thanks for your explanation.
Actually, it wasn't wise man, it is what is taught in most Universities
these days.
Lionel.
|
| |
|
| |
 |
Lew

|
Posted: 2007-9-29 10:54:00 |
Top |
java-programmer >> Formatting a string in Java
Jean-Baptiste Nizet wrote:
>>> while (formattedString.length() < 5) {
>>> StringBuffer tmp = new StringBuffer();
>>> tmp.append("0");
>>> tmp.append(formattedString);
>>> formattedString = tmp.toString();
Note the String creation inside the loop, which we should seek to avoid, no?
>>> }
Lew wrote:
>> Sigh.
>>
>> Here's a better loop:
>>
>> int len = formatted.length();
>> // why put "String" in the name of a String?
>> StringBuilder sb = new StringBuilder( "" );
>> while ( len++ < 5 )
>> {
>> sb.append( '0' );
>> }
>> formatted = sb.append( formatted ).toString();
>>
>> You can wrap the whole loop and reassignment in an
>> if ( len < 5 )
>> to short-circuit unnecessary reassignment of "formatted".
Jean-Baptiste Nizet wrote:
> Sigh.
>
> You should re-read my first post in this thread, then the reply from
> Lionel van den Berg, and my reply to his reply, to which you have just
> answered with a "Sigh".
> The text, in English, before and after the code snippets, is part of
> the post, and you should read it as well.
Can we say, "supercilious"?
> The code snippet was precisely there to explain to Lionel why he must not concatenate
> Strings inside loops, since doing it results in the same bytecode as
> the ugly loop above, with lots of StringBuffer and String creations.
If you're referring to the loop I posted, it had no StringBuffer nor String
creation inside the loop. It didn't even have any StringBuilder creation
inside the loop.
Actually, I did read it. My response quoted the relevant part of that
discussion. And your code re-instantiated Strings inside the loop, which is
quite nearly as bad.
My sigh was for the extra String being created inside the loop:
>>> formattedString = tmp.toString();
The StringBuilder approach I posted does not create lots of Strings. It
creates exactly one. Yours creates one in each loop iteration.
Thus the bytecode is different.
--
Lew
|
| |
|
| |
 |
Lew

|
Posted: 2007-9-29 10:59:00 |
Top |
java-programmer >> Formatting a string in Java
Jean-Baptiste Nizet wrote:
> You should re-read my first post in this thread, then the reply from
> Lionel van den Berg, and my reply to his reply, to which you have just
> answered with a "Sigh".
> The text, in English, before and after the code snippets, is part of
> the post, and you should read it as well. The code snippet was
> precisely there to explain to Lionel why he must not concatenate
> Strings inside loops, since doing it results in the same bytecode as
> the ugly loop above, with lots of StringBuffer and String creations.
Can we say, "supercilious"?
Yes, you are right. I reviewed the text and corrected my interpretation.
--
Lew
|
| |
|
| |
 |
Lew

|
Posted: 2007-9-29 11:04:00 |
Top |
java-programmer >> Formatting a string in Java
Jean-Baptiste Nizet wrote:
> You should re-read my first post in this thread, then the reply from
> Lionel van den Berg, and my reply to his reply, to which you have just
> answered with a "Sigh".
> The text, in English, before and after the code snippets, is part of
> the post, and you should read it as well. The code snippet was
> precisely there to explain to Lionel why he must not concatenate
> Strings inside loops, since doing it results in the same bytecode as
> the ugly loop above, with lots of StringBuffer and String creations.
I'll get this right yet.
Yes, you are correct. I have reviewed the text and corrected my interpretation.
I was trying to say the exact same thing you were, but got entangled in it and
confused. I think I have the sequence right now, though.
--
Lew
|
| |
|
| |
 |
Roedy Green

|
Posted: 2007-9-29 12:12:00 |
Top |
java-programmer >> Formatting a string in Java
On Fri, 28 Sep 2007 10:27:59 -0000, Jean-Baptiste Nizet
<email***@***.com> wrote, quoted or indirectly quoted someone who said
:
>System.out.println(format.format(Integer.parseInt("23")));
>System.out.println(format.format(Integer.parseInt("5")));
you could write that more simply as
>System.out.println(format.format(23));
>System.out.println(format.format(5));
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
|
| |
|
| |
 |
Roedy Green

|
Posted: 2007-9-29 12:13:00 |
Top |
java-programmer >> Formatting a string in Java
On Fri, 28 Sep 2007 02:28:00 -0700, Jerry Manner
<email***@***.com> wrote, quoted or indirectly quoted someone
who said :
>
>I am a newby in Java and am trying to format a string into a fixed
>number of positions( in this case 5).
>So if I have a "5" in should be "00005", and "23" should be "00023".
see StringTools.lz.
http://mindprod.com/products1.html#COMMON11.
It uses a technique similar to the append '0' in a loop, but without
the overhead.
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
|
| |
|
| |
 |
Arne Vajh鴍

|
Posted: 2007-10-9 10:45:00 |
Top |
java-programmer >> Formatting a string in Java
Jerry Manner wrote:
> I am a newby in Java and am trying to format a string into a fixed
> number of positions( in this case 5).
> So if I have a "5" in should be "00005", and "23" should be "00023".
>
> I hav tried looking at the classes 'import java.text.NumberFormat' and
> 'import java.text.Format', but I didn't get far.
>
> Can anyone help me how I can do this in java?
You have seen loop with String, loop with StringBuffer, loop
with StringBuilder.
May I suggest:
s = "00000".substring(s.length()) + s;
or if it may be longer than 5:
if(s.length() < 5) s = "00000".substring(s.length()) + s;
Arne
|
| |
|
| |
 |
Roedy Green

|
Posted: 2007-10-9 12:06:00 |
Top |
java-programmer >> Formatting a string in Java
On Fri, 28 Sep 2007 02:28:00 -0700, Jerry Manner
<email***@***.com> wrote, quoted or indirectly quoted someone
who said :
>I hav tried looking at the classes 'import java.text.NumberFormat' and
>'import java.text.Format', but I didn't get far.
see http://mindprod.com/jgloss/decimalformat.html
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
|
| |
|
| |
 |
Chris ( Val )

|
Posted: 2007-10-9 19:09:00 |
Top |
java-programmer >> Formatting a string in Java
On Sep 28, 9:59 pm, Lew <email***@***.com> wrote:
> Jean-Baptiste Nizet wrote:
> > while (formattedString.length() < 5) {
> > StringBuffer tmp = new StringBuffer();
> > tmp.append("0");
> > tmp.append(formattedString);
> > formattedString = tmp.toString();
> > }
>
> Sigh.
>
> > You see that lots of StringBuffer andStringinstances are created,
> > which makes the performance of such code terrible.
>
> Nothing wrong with creating lots of StringBuffers except that you should've
> used StringBuilder.
>
> Here's a better loop:
>
> int len = formatted.length();
> // why put "String" in the name of aString?
> StringBuilder sb = new StringBuilder( "" );
> while ( len++ < 5 )
> {
> sb.append( '0' );}
[snip]
It might pay to redesign the above in a way where
the field width of the can be altered dynamically
via an argument passed to a function or some such:
for( int index = 0;
index < ( fieldWidth - src.length() ); ++index ) {
sb.append( c );
}
A C++ std::string has an overloaded constructor
that allows you to pre allocate it with a specific
character as follows:
std::string s( '0', length );
I looked at Java' String class and StringBuilder
and unfortunately couldn't find an equivalent.
If Java has no operator overloading, how could I
create my own class to return a value?
E.g:
String s = MyString( '0', length );
Is that possible or do I have to build a method
for it and then call that?
String s = MyString( '0', length ).get();
Or...
String s = new MyString( '0', length ).get();
Thanks,
Chris
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- In praise of EclipseOn Sat, 16 Jul 2005 20:02:41 GMT, Dale King
<email***@***.com> wrote or quoted :
>As I said, you are actually not pointing to anything because the site
>doesn't exist, Rumsfeld explained nothing, and last I checked even if he
>had he is not a member of the Bush family.
The link has gone stale. The site itself still exists. Last time I
looked, a month or so ago it showed you a C-SPAN video of McKinney
going after Rumsfeld.
I spent 20 minutes unsuccessfully last night trying to find a new
source for it.
For more details on the loss/embezzlements see
http://mindprod.com/politics/iraqeconomics.html
This is not the forum to discuss. Try alt.politics.bush
--
Bush crime family lost/embezzled $3 trillion from Pentagon.
Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video.
http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm
Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes
- 2
- Vmx Smalltalk for JavaA Beta version of Vmx Smalltalk for Java is now available for download.
http://vmx-net.com/downloads/downloadjvm.php
Your comments are welcome,
email***@***.com
- 3
- JRE installation woesHi All
I have installed the latest version of Sun's JRE on my Windows XP Pro PC.
However, its "performance" is somewhere between abysmally slow and not at
all. If I e.g. open the Java Control Panel module and click on one of the
tabs, it takes over two minutes for that tab to display - this on a 3.4 GHz
dual-processor 4 GB memory PC. Java aplications run no better. It does seem
to "speed up" if I Alt-tab to another program and then Alt-tab back.
CPU load is negligible so clearly, the JRE is waiting for something that
occurs only rarely. But I have no idea where to look.
Any help will be very much appreciated.
Ebbe
- 4
- jboss 4.0.3 jboss portal 2.2.1hi
i am a one week newbie to j2ee world ( no java exp )
however i am to deploy application ( that is compiere ) onto existing
platform ( pentaho that is )
as per this date my assumptions are :
= point of integration would be in portal
= compiere application itself, war, would be deployed on jboss /deploy
= jsp be made to enable access from portal to war
could somebody help me on what is the definable steps to do the
integration?
- 5
- 6
- J2MEHello,
Are there any newsgroups or forums specifically for J2ME? I would like to
make a game for mobile devices but I don't know where to start.
Thanks in advance,
Steve
- 7
- Sun Wireless Toolkit gives SecurityException - please help.I have a midlet (not written by me), and I would like to analyze how it
works. Unfortunately I am not able to run this midlet. Everything compiles
fine but I receive an runtime exception during running sun WTK emulator.
Incorrect domain name, switching to 'untrusted'
java.lang.SecurityException: untrusted domain is not configured
at com.sun.midp.security.Permissions.forDomain(+98)
at com.sun.midp.dev.DevMIDletSuitImpl.create(+39)
at com.sun.midp.dev.DevMIDletSuitImpl.create(+62)
at com.sun.midp.main.Main.runLocalClass(+20)
at com.sun.midp.main.Main.main(+116)
Exception completed.
14945 bytecodes executed
0 thread switches
738 classes in the system (including system classes)
229 dynamic objects allocated (14588 bytes)
1 garbage collections (0 bytes coolected)
I am not able to fing any solution via google. I hav e found only some not
clear instruction to delete MIDP_HOME environment variable. But I have not
any MIDP_HOME on my system.
I have also found some advices to change something in
java.security and java.policy files.
Unforunately I don't know what to change. Anyone has any idea how to fix my
problem ??
I will be appreciate for any advice. Thanks in advance.
--
RaW
Please fill free to correct my English.
- 8
- [J2ME] UI /freezes/ after IOExceptionHi,
I have a MiDlet that starts a Thread through a Runnable, in which
there is IO activity:
Runnable runner = new Runnable() { // some IO stuff there };
Thread thd = new Thread(runner);
thd.start();
The application runs well, until I need to close the IO channels that
are opened in that separate Thread.
Of course, I catch the IOException in my Thread, and the Thread
completes properly (and dies...).
But after this catch, the UI is not responding: if I press a button the
menu will not show, and if I do some programmaticaly changes in the UI
it does not display and the call blocks (i.e. if I add an item in the
current screen, nothing happens and the next line --System.out.println--
doesn't execute).
I know the application didn't die, cause I have another Thread running a
'while' loop and printing "I am alive!" even when the UI freezes.
And also if I don't perform UI changes I can print stuff in the main Thread.
Any idea to help me ? Thank you.
--
JScoobyCed
What about a JScooby snack Shaggy ? ... Shaggy ?!
- 9
- Toward a generic Disk Sort for JavaI was thinking how you might go about writing a sort that could handle
more data than could fit in RAM. It handled the problem is Abundance
by checkpointing the app to disk to free up maximum RAM, then spawning
a copy of Opt-Tech sort. My records were roughly like DataOutputStream
would produce, so I could automatically generate the command script
sort the fields in any way I wanted.
I thought you might pull it off in Java this way.
1. You write a comparator as if you were going to sort Objects in an
ArrayList.
2. the external sort has an add method that also takes collections.
It accepts a "chunk" of records, and sorts them using Sun's sort.
Then it writes them out as SERIALISED objects in heavily buffered
stream. There may be some way to do a partial reset after each object
to speed it up.
Then you repeat collecting, sorting and writing another batch to
another file.
When you have created N files, you recycle, appending. (Optimal N to
be determined by experiment). Ideally each file would be on a
different physical drive.
Then when all the records have been added, you start merging chunks
into longer chunks, and writing out the longer chunks. Each N-way
merge cuts the number of chunks by 1/N and increases the length of the
chunks N times.
on the final merge pass does not happen until the user invokes the
Iterator to hand over the resulting records.
Another way it might be done is the records to be sorted must by byte
arrays, chunks effectively produced by DataOutputStream. You specify
offset, length and key type e.g.
int, byte, short, float, double, String.
This would require a detailed knowledge of the bit structure of the
records, the way you did in the olden days of assembler and C.
This would be clumsier to use, but would avoid the overhead of
pickling and reconstituting records on every pass.
Then of course, there is the possibility someone has already solved
this and done it well.
The universe has a sneaky habit. Problems start out small, and it
looks like a purely in RAM solution is perfectly adequate. Then they
bit by bit grow and grow and start pushing the limits of the RAM
solution. Suddenly you are faced with a major redesign.
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
- 10
- Expanding on Video Formats
I'm wondering if somebody with java knowledge will be able answer my
question.
Would it be within the realms of possibility to create a web-based
video editing suite? (Which media format -- Windows, Quicktime, etc. --
might best lend itself to such a task?)
Also, I imagine that this application may require a desaturation
process to bring down the memory size for the raw footage.
I don't know enough about java programming to even guess about this;
but with the current prevalence of digital editing software, an online
version has convenience written all over it.
Thanks,
- 11
- Generics and returning specific subclass from methodI have an abstract class called say Base and two subclasses, say Sub1 and
Sub2. Let me define a method in Super which I want to return a new instance
of the superclass itself but I want to access this without having to cast.
IE,
public class Super {
public <E extends Super> E partialCopy() {
return this; // return this for example
}
}
public class Sub1 extends Super { }
Then I want to do this without the cast.
Sub1 s1 = new Sub1();
Sub2 s2 = s1.partialCopy();
Can I do this with generics ?
- 12
- AbstractTableModel not compatible with SwingWhat happens when AbstractTableModel is no longer compatible with Swing?
I kinda see how to use it, but don't see how XMLEncoder would work in its
place.
"Warning: Serialized objects of this class will not be compatible with
future Swing releases. The current serialization support is appropriate
for short term storage or RMI between applications running the same
version of Swing. As of 1.4, support for long term storage of all
JavaBeansTM has been added to the java.beans package. Please see
XMLEncoder. "
http://java.sun.com/javase/6/docs/api/javax/swing/table/
AbstractTableModel.html
thanks,
Thufir
- 13
- set guarded blockHow I can define, modify, delete a guarded block in NetBeans?
The gaurded block is writen by me (not by IDE).
Where is documentation about writing guarded block?
--
WOJSAL
http://www.wojsal.prv.pl
- 14
- J2ME Server on a PCI have a question about J2ME using bluetooth. I am trying to implement
a client server applicatin between my phone (Nokia 6630) and my PC. I
can send data over bluetooth to the PC on a virtual serial port but I
need a way to "catch" the data I sent on the PC end and turn it back
into an image. Are there any applications out there that do this
already? Can I run a J2ME server on my PC? Thanks
Mike
- 15
- Bug in java.net.Socket close() behavior?According to the API for java.net.Socket close():
"Any thread currently blocked in an I/O operation upon this socket
will throw a SocketException."
http://java.sun.com/j2se/1.5.0/docs/api/java/net/Socket.html#close()
I have observed that java 1.5 on FreeBSD does not follow this while
the Windows and Linux ones I have tested do. On the FreeBSD runtimes
that I have tested, a thread blocked on reading a socket just hangs
forever if the socket is closed.
Attached is a simple program that tests this behavior. It just
connects to a port on one of my servers and has a reader thread
watching input from the socket and closes the socket in a different
thread to see if the reader thread gets an exception.
Java runtimes that I have tested this on:
# java -version
java version "1.5.0"
Java(TM) 2 Runtime Environment, Standard Edition (build diablo-1.5.0-b01)
Java HotSpot(TM) 64-Bit Server VM (build diablo-1.5.0_07-b01, mixed mode)
# java -version
java version "1.5.0-p2"
Java(TM) 2 Runtime Environment, Standard Edition (build
1.5.0-p2-root_07_mar_2006_02_41)
Java HotSpot(TM) 64-Bit Server VM (build
1.5.0-p2-root_07_mar_2006_02_41, mixed mode)
|
|
|