はじめに
* 漢数字をアラビア数字に変換する必要があり、ネットを漁ってたらよさげなサンプルがあったのだが
一部バグがあったので修正してサンプルをアップする
サンプル
* 正の整数のみ(小数や負の数は未対応)
Converter.java
import java.security.InvalidParameterException;
public class Converter {
/**
* デモ.
* @param args
*/
public static void main(String[] args) {
System.out.println(Converter.convertPositiveKanjiNumber("零"));
System.out.println(Converter.convertPositiveKanjiNumber("三"));
System.out.println(Converter.convertPositiveKanjiNumber("二千五百"));
System.out.println(Converter.convertPositiveKanjiNumber("三千"));
System.out.println(Converter.convertPositiveKanjiNumber("一億五千万"));
System.out.println(Converter.convertPositiveKanjiNumber("一億五千万四"));
System.out.println(Converter.convertPositiveKanjiNumber("千十一"));
System.out.println(Converter.convertPositiveKanjiNumber("二十一億三千百五万千二十一"));
System.out.println(Converter.convertPositiveKanjiNumber("十一億七百一万十一"));
}
/**
* 漢数字(正の整数)(をアラビア数字(int型)に変換する
* @param targetValue 対象値(漢字・正の整数)
* @return 正の整数(int型)
*/
public static int convertPositiveKanjiNumber(String targetValue) {
if (targetValue == null || "".equals(targetValue)) {
throw new IllegalArgumentException("Empty");
}
if ("零".equals(targetValue)) {
return 0;
}
int firstDegit = 1;
int fourthDegit = 0;
int total = 0;
for (int i = 0; i < targetValue.length(); i++) {
char kanjiNumber = targetValue.charAt(i);
switch (kanjiNumber) {
case '一':
firstDegit = 1;
break;
case '二':
firstDegit = 2;
break;
case '三':
firstDegit = 3;
break;
case '四':
firstDegit = 4;
break;
case '五':
firstDegit = 5;
break;
case '六':
firstDegit = 6;
break;
case '七':
firstDegit = 7;
break;
case '八':
firstDegit = 8;
break;
case '九':
firstDegit = 9;
break;
case '十':
fourthDegit += (firstDegit != 0 ? firstDegit : 1) * 10;
firstDegit = 0;
break;
case '百':
fourthDegit += (firstDegit != 0 ? firstDegit : 1) * 100;
firstDegit = 0;
break;
case '千':
fourthDegit += (firstDegit != 0 ? firstDegit : 1) * 1_000;
firstDegit = 0;
break;
case '万':
fourthDegit += firstDegit;
total += (fourthDegit != 0 ? fourthDegit : 1) * 10_000;
fourthDegit = 0;
firstDegit = 0;
break;
case '億':
fourthDegit += firstDegit;
total += (fourthDegit != 0 ? fourthDegit : 1) * 100_000_000;
fourthDegit = 0;
firstDegit = 0;
break;
default:
throw new InvalidParameterException("Found invaid parameter : " + kanjiNumber);
}
}
return total + fourthDegit + firstDegit;
}
}
出力結果
0
3
2500
3000
150000000
150000004
1011
2131051021
1107010011