Java Formatting with Correct Plurals - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Java Formatting with Correct Plurals - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, January 2, 2019

Java Formatting with Correct Plurals

Java Formatting with Correct Plurals

Problem

You’re printing something like "We used " + n + " items" , but in English, “We used 1
items” is ungrammatical. You want “We used 1 item.”

Solution

Use a ChoiceFormat or a conditional statement.

Use Java’s ternary operator ( cond ? trueval : falseval ) in a string concatenation.
Both zero and plurals get an “s” appended to the noun in English, so we test for n==1 .

// FormatPlurals.java
public static void main(String argv[]) {
report(0);
report(1);
report(2);
}
/** report -- using conditional operator */
public static void report(int n) {
System.out.println("We used " + n + " item" + (n==1?"":"s"));
}

Does it work?

$ java FormatPlurals
We used 0 items
We used 1 item
We used 2 items
$

The final println statement is short for:

if (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:

import java.text.*;
/**
* Format a plural correctly, using a ChoiceFormat.
*/
public class FormatPluralsChoice extends FormatPlurals {
static double[] limits = { 0, 1, 2 };
static String[] formats = { "items", "item", "items"};
static ChoiceFormat myFormat = new ChoiceFormat(limits, formats);
/** report -- using conditional operator */
public static void report(int n) {
System.out.println("We used " + n + " " + myFormat.format(n));
}
public static void main(String[] argv) {
report(0);
report(1);
report(2);
}
}

This generates the same output as the basic version. It is slightly longer, but more general, and lends itself better to internationalization.

No comments:

Post a Comment

Post Top Ad