Java Mania

Java Mania

ChoiceFormat

ある範囲の数値にフォーマットを追加するクラス。 例えば、月の計算時に「0=1月」、「1=2月」、「2=3月」のように数値によって決められた文字にすることができる。 サンプルソースを作成しているときに、データベースへのインプット、アウトプット時のデータ整形処理で重宝する 気がした。個人的にはSQL文でデータを整形する方が好きだが。
HomePageTop▲

How To Use -使用方法-

ChoiceFormatクラスは下記のように使用する。

※コンストラクタについてはサンプルソースを見てもらった方が分かりやすい。

コンストラクタの説明

ChoiceFormat(String newPattern)
指定されたフォーマットパターンのオブジェクトを生成する。
ChoiceFormat(double[] limits,String[] formats)
第1引数のリミットとそれに対応する第2引数のフォーマットによりオブジェクトを生成する。
メソッドの説明
※全てのメソッドを網羅していないので、詳細はAPIリファレンスを参照する。
public void applyPattern(String newPattern)
新しいフォーマットパターンを設定する。
public final String format(long/double number)
フォーマット処理を行なう。
public Object[] getFormats()
フォーマットを取得する。
public double[] getLimits()
リミットを取得する。
HomePageTop▲

Source -ChoiceFormatTest.java-

package mania.test;

import java.text.ChoiceFormat;

public class ChoiceFormatTest
{

  // ChoiceFormatの使用方法
  public static void main(String[] args)
  {
    System.out.println("===実行結果===");

    // limitの設定
    double[] limits = { 1, 2, 3, 4, 5 };

    // formatの設定
    String[] formats = { "Jan", "Feb", "Mar", "Apr", "May" };

    // ChoiceFormatのインスタンスを生成
    ChoiceFormat format1 = new ChoiceFormat(limits, formats);

    // 数値をフォーマット
    for(int i = 1; i <= limits.length; i ++ )
    {
      System.out.println(i + "月:" + format1.format(i));
    }

    // ChoiceFormatのインスタンスを生成(パターンを指定)
    //format1.applyPattern("-1#Negative| 0#Zero| 0<Positive")でも同じ。
    ChoiceFormat format2 = new ChoiceFormat("-1#Negative| 0#Zero| 0<Positive");
    System.out.println("-4:" + format2.format( - 4));
    System.out.println(" 0:" + format2.format(0));
    System.out.println("10:" + format2.format(10));
  }
}
HomePageTop▲

Results -実行結果-


===実行結果===
1月:Jan
2月:Feb
3月:Mar
4月:Apr
5月:May
-4:Negative
 0:Zero
10:Positive

HomePageTop▲

Copyright (C) 2006, JavaMania. All Rights Reserved.