Java Reference
In-Depth Information
public
public class
class
FormatPlurals
FormatPlurals
{
public
public static
static
void
void
main
(
String
[]
argv
) {
report
(
0
);
report
(
1
);
report
(
2
);
}
/** report -- using conditional operator */
public
public static
int
n
) {
System
.
out
.
println
(
"We used "
+
n
+
" item"
+ (
n
==
1
?
""
:
"s"
));
static
void
void
report
(
int
}
}
Does it work?
$
java numbers.FormatPlurals
We used 0 items
We used 1 item
We used 2 items
$
The final
println
statement is effectively equivalent to:
iif
(
n
==
1
)
System
.
out
.
println
(
"We used "
+
n
+
" item"
);
else
System
.
out
.
println
(
"We used "
+
n
+
" items"
);
This is a lot longer, in fact, so the ternary conditional operator is worth learning.
The
ChoiceFormat
is ideal for this. It is actually capable of much more, but here I'll show
only this simplest use. I specify the values 0, 1, and 2 (or more), and the string values to print
corresponding to each number. The numbers are then formatted according to the range they
fall into:
public
public class
class
FormatPluralsChoice
FormatPluralsChoice
extends
extends
FormatPlurals
{
// ChoiceFormat to just give pluralized word
static
static
double
double
[]
limits
= {
0
,
1
,
2
};
static
static
String
[]
formats
= {
"reviews"
,
"review"
,
"reviews"
};
static
static
ChoiceFormat pluralizedFormat
=
new
new
ChoiceFormat
(
limits
,
formats
);