Re: print("my name is {name}, and {age}-year old {gender}", name, age, gender);
- From: Chris Smith <cdsmith@xxxxxxx>
- Date: Fri, 30 Dec 2005 19:15:07 -0700
moop? <samhng@xxxxxxxxx> wrote:
> In C# print functions, the syntax is like
> print("my name is{0}, and {1}-year old {2}", name, age, gender);
See java.text.MessageFormat for a Java equivalent. Print
(Writer/Stream).printf is also similar. The choice depends on what
exactly you're trying to accomplish. MessageFormat tends to work better
for abstract localization work, whereas the printf style syntax is
better for precise formatting.
> But I want to do a little further to make the print function knows
> which argument is going to fill the slot in the pattern string, even
> the arguments are not ordered in place:
> print("my name is {name}, and {age}-year old {gender}", age, gender,
> name);
>
> or it will have exception burst out when there is no suitable
> paramenter:
> print("hello, {name}", age);
>
> can we do that?
No, you can't do that. The reason is that a method is not privy to the
expressions that resulted in the actual parameters. In fact, that
information isn't preserved past the compiler except in debugging info,
so it can't possibly be available at runtime. As a side-note, I'm very
glad that you can't do that. Do you really mean to make it impossible
for someone to call that function unless they name their local variables
as you want them to? That's sorta ridiculous.
Note that you don't need to pass the parameters in order, though. Thus,
you can say:
> print("my name is {2}, and {0}-year old {1}", age, gender, name);
You could also write an equivalent using a Map<String,Object> so that
real names are associated with the objects instead of just local
variable names.
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
.
- References:
- Prev by Date: Our Solution Guide and material is better than Ten (10) Mock tests in exa
- Next by Date: Tomcat 5* and javaw.exe
- Previous by thread: Re: print("my name is {name}, and {age}-year old {gender}", name, age, gender);
- Next by thread: Our Solution Guide and material is better than Ten (10) Mock tests in exa
- Index(es):