choiceformat_ChoiceFormat:数字范围格式
choiceformat
ChoiceFormat類的Javadoc指出ChoiceFormat “允許您將格式附加到一系列數字上”,并且“通常在MessageFormat中用于處理復數”。 這篇文章描述了java.text.ChoiceFormat并提供了一些在Java代碼中應用它的示例。
ChoiceFormat與java.text包中其他“ 格式 ”類之間最明顯的區別之一是ChoiceFormat不提供用于訪問ChoiceFormat實例的靜態方法。 相反, ChoiceFormat提供了兩個用于實例化ChoiceFormat對象的構造函數。 用于ChoiceFormat的Javadoc重點說明了這一點:
ChoiceFormat與其他Format類的不同之處在于,您使用構造函數(而不是使用getInstance樣式工廠方法)創建ChoiceFormat對象。 不需要工廠方法,因為ChoiceFormat不需要為給定語言環境進行任何復雜的設置。 實際上, ChoiceFormat不會實現任何特定ChoiceFormat語言環境的行為。
用兩個數組構造ChoiceFormat
ChoiceFormat提供的兩個構造函數中的第一個接受兩個數組作為其參數。 第一個數組是原始雙精度數組,表示每個間隔的最小值(起始值)。 第二個數組是一個字符串數組,代表與每個時間間隔關聯的名稱。 這兩個數組必須具有相同數量的元素,因為在數字(雙)間隔和描述這些間隔的字符串之間存在假定的一對一映射。 如果兩個數組的元素數量不同,則會遇到以下異常。
線程“主”中的異常java.lang.IllegalArgumentException:數組和限制數組的長度必須相同。
ChoiceFormat(double [],String [])構造函數的Javadoc說明第一個數組參數名為“ limits”,類型為double[] ,并被描述為“升序限制”。 第二個數組參數名為“ formats”,類型為String[] ,并被描述為“相應的格式字符串”。 根據Javadoc,此構造函數“以限制和相應的格式進行構造”。
下一個代碼清單中演示了使用ChoiceFormat構造函數接受兩個數組參數的writeGradeInformation(ChoiceFormat)稍后將顯示writeGradeInformation(ChoiceFormat)方法和fredsTestScores變量)。
/*** Demonstrate ChoiceFormat instantiated with ChoiceFormat* constructor that accepts an array of double and an array* of String.*/ public void demonstrateChoiceFormatWithDoublesAndStringsArrays() {final double[] minimumPercentages = {0, 60, 70, 80, 90};final String[] letterGrades = {"F", "D", "C", "B", "A"};final ChoiceFormat gradesFormat = new ChoiceFormat(minimumPercentages, letterGrades);writeGradeInformation(fredsTestScores, gradesFormat); }上面的示例滿足了圖示的ChoiceFormat構造函數的期望。 這兩個數組的元素數相同,第一個( double[] )數組的元素按升序排列,第二個( String[] )數組的“格式”與相應的間隔開始限制值相同在第一個數組中。
上面的代碼片段中引用的writeGradeInformation(ChoiceFormat)方法演示了如何使用基于兩個數組的ChoiceFormat實例來“格式化”作為字符串的提供的數值。 接下來顯示該方法的實現。
/*** Write grade information to standard output* using the provided ChoiceFormat instance.** @param testScores Test Scores to be displayed with formatting.* @param gradesFormat ChoiceFormat instance to be used to format output.*/ public void writeGradeInformation(final Collection<Double> testScores,final ChoiceFormat gradesFormat) {double sum = 0;for (final Double testScore : testScores){sum += testScore;out.println(testScore + " is a '" + gradesFormat.format(testScore) + "'.");}double average = sum / testScores.size();out.println("The average score (" + average + ") is a '"+ gradesFormat.format(average) + "'."); }上面的代碼使用提供的ChoiceFormat實例來“格式化”測試成績。 “格式”不是打印數字值,而是打印與數字值所在的時間間隔關聯的字符串。 下一個代碼清單顯示了這些示例中使用的fredsTestScores的定義。
private static List<Double> fredsTestScores; static {final ArrayList<Double> scores = new ArrayList<>();scores.add(75.6);scores.add(88.8);scores.add(97.3);scores.add(43.3);fredsTestScores = Collections.unmodifiableList(scores); }通過用兩個數組實例化的ChoiceFormat實例運行這些測試分數,將產生以下輸出:
75.6 is a 'C'. 88.8 is a 'B'. 97.3 is a 'A'. 43.3 is a 'F'. The average score (76.25) is a 'C'.使用模式字符串構造ChoiceFormat
接受基于String的模式的ChoiceFormat(String)構造函數可能對那些愿意使用具有類似格式化類的基于String的模式(如DateFormat和DecimalFormat)的開發人員更具吸引力。 下一個代碼清單演示了此構造函數的用法。 提供給構造函數的模式會導致ChoiceFormat實例,該實例的格式應與前面示例中使用帶有兩個數組的構造函數創建的ChoiceFormat實例相同。
/*** Demonstrate ChoiceFormat instantiated with ChoiceFormat* constructor that accepts a String pattern.*/ public void demonstrateChoiceFormatWithStringPattern() {final String limitFormatPattern = "0#F | 60#D | 70#C | 80#B | 90#A";final ChoiceFormat gradesFormat = new ChoiceFormat(limitFormatPattern);writeGradeInformation(fredsTestScores, gradesFormat); }此處調用的writeGradeInformation方法與之前調用的方法相同,并且輸出也相同(此處未顯示,因為相同)。
極限和邊界上的ChoiceFormat行為
到目前為止,這些示例在預期范圍內的測試成績上都運行良好。 現在將使用另一組測試成績來演示ChoiceFormat其他一些功能。 這組新的測試分數將在下一個代碼清單中設置,其中包括“不可能”的否定分數和另一個“可能”高于100的分數。
private static List<Double> boundaryTestScores; static {final ArrayList<Double> boundaryScores = new ArrayList<Double>();boundaryScores.add(-25.0);boundaryScores.add(0.0);boundaryScores.add(20.0);boundaryScores.add(60.0);boundaryScores.add(70.0);boundaryScores.add(80.0);boundaryScores.add(90.0);boundaryScores.add(100.0);boundaryScores.add(115.0);boundaryTestScores = boundaryScores; }當以上測試分數集通過之前創建的兩個ChoiceFormat實例運行時,輸出如下所示。
-25.0 is a 'F '. 0.0 is a 'F '. 20.0 is a 'F '. 60.0 is a 'D '. 70.0 is a 'C '. 80.0 is a 'B '. 90.0 is a 'A'. 100.0 is a 'A'. 115.0 is a 'A'. The average score (56.666666666666664) is a 'F '.剛剛顯示的輸出表明ChoiceFormat構造函數中設置的“限制”是“包含的”,這意味著這些限制適用于指定的限制和更高的限制(直到下一個限制)。 換句話說,數字范圍被定義為大于或等于指定的限制。 ChoiceFormat的Javadoc文檔使用數學描述對此進行了描述:
當且僅當limit [j]≤X <limit [j + 1]時,X與j匹配
邊界測試分數示例的輸出還演示了Javadoc文檔中描述的ChoiceFormat另一個特征:“如果不匹配,則使用第一個或最后一個索引,具體取決于數字(X)太低還是太低”高?!?因為在提供的ChoiceFormat實例中不存在-25.0的匹配項,所以將最低范圍(最低限度為“ F”)應用于低于最低范圍的那個數字。 在這些測試成績示例中,沒有為“ A”指定比“ 90”更高的限制,因此所有高于90的分數(包括高于100的分數)都針對“ A”。 假設我們想要將分數范圍強制在0到100之間,或者對于小于0或大于100的分數,將格式化結果指示為“無效”。這可以如下面的代碼清單所示。
/*** Demonstrating enforcing of lower and upper boundaries* with ChoiceFormat instances.*/ public void demonstrateChoiceFormatBoundariesEnforced() {// Demonstrating boundary enforcement with ChoiceFormat(double[], String[])final double[] minimumPercentages = {Double.NEGATIVE_INFINITY, 0, 60, 70, 80, 90, 100.000001};final String[] letterGrades = {"Invalid - Too Low", "F", "D", "C", "B", "A", "Invalid - Too High"};final ChoiceFormat gradesFormat = new ChoiceFormat(minimumPercentages, letterGrades);writeGradeInformation(boundaryTestScores, gradesFormat);// Demonstrating boundary enforcement with ChoiceFormat(String)final String limitFormatPattern = "-\u221E#Invalid - Too Low | 0#F | 60#D | 70#C | 80#B | 90#A | 100.0<Invalid - Too High";final ChoiceFormat gradesFormat2 = new ChoiceFormat(limitFormatPattern);writeGradeInformation(boundaryTestScores, gradesFormat2); }執行上述方法時,其輸出顯示兩種方法都更好地執行了邊界條件。
-25.0 is a 'Invalid - Too Low'. 0.0 is a 'F'. 20.0 is a 'F'. 60.0 is a 'D'. 70.0 is a 'C'. 80.0 is a 'B'. 90.0 is a 'A'. 100.0 is a 'A'. 115.0 is a 'Invalid - Too High'. The average score (56.666666666666664) is a 'F'. -25.0 is a 'Invalid - Too Low '. 0.0 is a 'F '. 20.0 is a 'F '. 60.0 is a 'D '. 70.0 is a 'C '. 80.0 is a 'B '. 90.0 is a 'A '. 100.0 is a 'A '. 115.0 is a 'Invalid - Too High'. The average score (56.666666666666664) is a 'F '.最后一個代碼清單演示了如何使用Double.NEGATIVE_INFINITY和\u221E ( Unicode INFINITY字符 )在每個示例中建立最低限度的邊界。 對于高于100.0的分數,如果將其格式化為無效分數,則基于數組的ChoiceFormat使用一個稍大于100的數字作為該無效范圍的下限。 基于字符串/模式的ChoiceFormat實例在使用小于號(<)來將“無效–過高”范圍的下限指定為大于100.0的任何數字時,提供了更大的靈活性和準確性。
使用ChoiceFormat處理無,單數和復數
我通過引用Javadoc來打開這篇文章,指出ChoiceFormat是“通常在MessageFormat中用于處理復數形式”,但尚未在本文中演示這種常用用法。 為了完整起見 ,我將在此處非常簡短地演示其中的一部分(沒有MessageFormat的復數),但是Java教程的 “ 處理復數”課 ( 國際化的一部分)中提供了ChoiceFormat的這種常用用法的更完整的說明(帶有MessageFormat的復數)。 徑 )。
下一個代碼清單演示了ChoiceFormat在處理單數和復數情況下的應用。
/*** Demonstrate ChoiceFormat used for differentiation of* singular from plural and none.*/ public void demonstratePluralAndSingular() {final double[] cactiLowerLimits = {0, 1, 2, 3, 4, 10};final String[] cactiRangeDescriptions ={"no cacti", "a cactus", "a couple cacti", "a few cacti", "many cacti", "a plethora of cacti"};final ChoiceFormat cactiFormat = new ChoiceFormat(cactiLowerLimits, cactiRangeDescriptions);for (int cactiCount = 0; cactiCount < 11; cactiCount++){out.println(cactiCount + ": I own " + cactiFormat.format(cactiCount) + ".");} }運行最后一個代碼清單中的示例將導致輸出,如下所示。
0: I own no cacti. 1: I own a cactus. 2: I own a couple cacti. 3: I own a few cacti. 4: I own many cacti. 5: I own many cacti. 6: I own many cacti. 7: I own many cacti. 8: I own many cacti. 9: I own many cacti. 10: I own a plethora of cacti.ChoiceFormat模式支持的最后一個符號
\u2264 ( ≤ )是ChoiceFormat模式分析可識別的另一種符號,用于根據生成的數值格式化字符串。 在下一個代碼清單以及該代碼清單之后的代碼輸出中對此進行了演示。 請注意,在此示例中, \u2264工作原理與使用前面顯示的更簡單的#號相同。
/*** Demonstrate using \u2264 in String pattern for ChoiceFormat* to represent >= sign. Treated differently than less-than* sign but similarly to #.*/ public void demonstrateLessThanOrEquals() {final String limitFormatPattern = "0\u2264F | 60\u2264D | 70\u2264C | 80\u2264B | 90\u2264A";final ChoiceFormat gradesFormat = new ChoiceFormat(limitFormatPattern);writeGradeInformation(fredsTestScores, gradesFormat); }75.6 is a 'C '. 88.8 is a 'B '. 97.3 is a 'A'. 43.3 is a 'F '. The average score (76.25) is a 'C '.評論中的觀察
在本節中,我總結了本文及其示例過程中有關ChoiceFormat一些觀察。
- 當使用ChoiceFormat(double [],String [])構造函數時 ,兩個傳入的數組必須具有相同的大小,否則將引發IllegalArgumentException (“ Array和limit數組必須具有相同的長度?!?#xff09;。
- 提供給ChoiceFormat(double [],String [])構造函數的“ limits” double[]數組應具有從左到右以數字升序排列的限制。 如果不是這種情況,則不會引發任何異常,但是邏輯幾乎肯定不會正確,因為針對ChoiceFormat實例進行格式化的字符串將錯誤地“匹配”。 同樣的期望也適用于接受模式的構造函數。
- ChoiceFormat允許Double.POSITIVE_INFINITY和Double.NEGATIVE_INFINITY通過其兩個數組的構造函數用于指定范圍下限。
- ChoiceFormat允許\u221E和-\u221E通過其單個String(模式)構造函數來指定較低的范圍限制。
- ChoiceFormat構造函數接受String模式比雙數組構造函數靈活一些,并且允許將下限邊界指定為一定數量范圍內的所有內容,而不必確切地包含該特定數量。
- 提供給單個String ChoiceFormat構造函數的String模式中具有特殊含義的符號和字符包括# , < , \u2264 ( ≤ ), \u221E ( ∞ )和| 。
結論
ChoiceFormat允許自定義數字范圍的格式,以便特定范圍可以具有不同和特定的表示形式。 這篇文章涵蓋了使用ChoiceFormat進行數字范圍格式化的幾個不同方面,但是這篇文章中沒有涉及使用ChoiceFormat 從字符串中解析數字范圍 。
進一步閱讀
- ChoiceFormat API文檔
- 處理復數
- 文本:消息格式的自由–第2部分:選擇格式
- 使用ChoiceFormat的Java i18n多元化
- ChoiceFormat有什么問題? (翻譯后的內容–第四部分)
- 進一步了解ChoiceFormat的問題
翻譯自: https://www.javacodegeeks.com/2014/09/choiceformat-numeric-range-formatting.html
choiceformat
總結
以上是生活随笔為你收集整理的choiceformat_ChoiceFormat:数字范围格式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 递归分解WAR文件
- 下一篇: netbeans ide_IDE:5个最