codice:
public class TestNumeroLetterale
{
public static void main (String[] args)
{
if (args.length == 1)
{
try
{
test (Integer.parseInt (args[0]));
}
catch (Exception e)
{
System.out.println (e);
}
}
else
{
test (0);
test (1);
test (12);
test (123);
test (1234);
test (12345);
test (123456);
test (1234567);
test (12345678);
test (123456789);
test (1234567890);
}
}
public static void test (int num)
{
System.out.println (num + " = " + NumeroLetterale.format (num));
}
}
class NumeroLetterale
{
private static final String[] strings00X =
{
"", "uno", "due", "tre", "quattro",
"cinque", "sei", "sette", "otto", "nove"
};
private static final String[] strings01X =
{
"dieci", "undici", "dodici", "tredici", "quattordici",
"quindici", "sedici", "diciassette", "diciotto", "diciannove"
};
private static final String[] strings0X0 =
{
"", "", "vent", "trent", "quarant",
"cinquant", "sessant", "settant", "ottant", "novant"
};
private static void formatGroup (StringBuilder sb, int group, String unit1, String unit2)
{
group %= 1000;
if (group == 1)
{
sb.append (unit1);
}
else
{
int digit1 = group / 100;
int digit2 = (group / 10) % 10;
int digit3 = group % 10;
if (digit1 > 0)
{
if (digit1 > 1)
sb.append (strings00X[digit1]);
sb.append ("cento");
}
if (digit2 == 0)
sb.append (strings00X[digit3]);
else if (digit2 == 1)
sb.append (strings01X[digit3]);
else
{
sb.append (strings0X0[digit2]);
if (digit3 != 1 && digit3 != 8)
sb.append (digit2 == 2 ? 'i' : 'a');
sb.append (strings00X[digit3]);
}
if (group != 0)
sb.append (unit2);
}
}
public static String format (int number)
{
if (number < 0)
throw new IllegalArgumentException ("number cannot be negative");
StringBuilder sb = new StringBuilder ();
if (number == 0)
sb.append ("zero");
else
{
formatGroup (sb, number / 1000000000, "unmiliardo", "miliardi");
formatGroup (sb, number / 1000000, "unmilione", "milioni");
formatGroup (sb, number / 1000, "mille", "mila");
formatGroup (sb, number, "uno", "");
}
return sb.toString ();
}
}