当前位置: 代码迷 >> 综合 >> Android 系列 6.28使用正确的复数格式化
  详细解决方案

Android 系列 6.28使用正确的复数格式化

热度:80   发布时间:2024-01-19 16:23:17.0
6.28使用正确的复数格式化
问题
你显示的是“找到”+ n +“评论”,但在英语中,“发现1评论”是不合语法。你想要“找到1评论”的情况下n == 1。
解
对于简单的,仅英语的结果,使用条件语句。为了更好的结果,这可以国际化,使用ChoiceFormat。在Android上,您可以在XML资源文件中使用<plural>。
讨论
“快速和脏”方法是在字符串连接中使用Java的三元运算符(cond?trueval:falseval)。因为在英语中,对于大多数名词,零和复数都用 s 英语附加到名词上(“没有书,一本书,两本书”),我们只需要测试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("Found " + n + " item" + (n==1?"":"s"));
}
在Java SE上作为主程序运行此程序将显示以下输出:
$ java FormatPlurals
Found 0 items
Found 1 item
Found 2 items
$
最后的println()语句是:
if (n==1)
System.out.println("Found " + n + " item");
else
System.out.println("Found " + n + " items");

这更长,所以Java的三元条件运算符值得学习。
当然,你不能任意使用这个,因为英语是一个奇怪的和有些特殊的语言。一些名词,如公共汽车,在末尾需要“es”,而其他的,如现金,是没有复数的集体名词(你可以有两群鹅或两叠现金,但你不能有“两个geeses”或“两个现金”)。一些名词,如鱼,可以被认为是复数,虽然鱼也是正确的复数。
一个更好的方法
java.text中的ChoiceFormat类是处理复数的理想选择;它允许您在名词上指定单数和复数(或更一般地,范围)变体。它能够更多,但在示例6-35中,我将只显示一些更简单的用法。我指定值0,1和2(或更多),以及要打印的字符串值对应于每个数字。然后根据它们落入的范围来格式化数字。
实例6-35。使用ChoiceFormat格式化复数
import java.text.*;
/**
* Format a plural correctly, using a ChoiceFormat.*/
public class FormatPluralsChoice extends FormatPlurals {
// ChoiceFormat to just give pluralized word
static double[] limits = { 0, 1, 2 };
static String[] formats = { "reviews", "review", "reviews"};
static ChoiceFormat pluralizedFormat =
new ChoiceFormat(limits, formats);
// ChoiceFormat to give English text version, quantified
static ChoiceFormat quantizedFormat = new ChoiceFormat(
"0#no reviews|1#one review|1<many reviews");
// Test data
static int[] data = { -1, 0, 1, 2, 3 };
public static void main(String[] argv) {
System.out.println("Pluralized Format");
for (int i : data) {
System.out.println("Found " + i + " " +
pluralizedFormat.format(i));
}
System.out.println("Quantized Format");
for (int i : data) {
System.out.println("Found " +
quantizedFormat.format(i));
}
}
}

这两个循环中的任一个都生成类似于基本版本的输出。使用ChoiceFormat的代码稍长,但更一般,并且更适合国际化。将“量化”形式构造函数的字符串放入strings.xml中,它将是本地化操作的一部分。
最佳方式(仅限Android)
在/res/values/<somefilename>.xml中创建一个包含如下内容的文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<plurals name="numberOfSongsAvailable">
<item quantity="one">One item found.</item>
<item quantity="other">%d items found.</item>
</plurals>
</resources>
在您的代码中,然后使用以下:
int count = getNumberOfsongsAvailable();
Resources res = getResources();
String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable, count);

我们建议使用XML资源。
  相关解决方案