Jan 31

The following example shows how recusion can be used to convert any number from 0 to 99 into words. eg. NumberToWords.numberToWords(34) returns “Thirty Four”.


public class NumberToWords {

	private static final String[] ONES = {
		"Zero", "One", "Two", "Three", "Four", "Five",
		"Six", "Seven", "Eight", "Nine" };
	private static final String[] TEENS = {
		"Ten", "Eleven", "Twelve", "Thirteen", null, "Fifteen",
		null, null, "Eighteen", null };
	private static final String[] TENS = {
		null, null, "Twenty", "Thirty", "Forty", "Fifty",
		"Sixty", "Seventy", "Eighty", "Ninety" };

	public static String numberToWords(int number) {
		if (number<10) {
			return ONES[number];
		} else if (number<20) {
			int n = number - 10;
			String words = TEENS[n];
			return words==null ? ONES[n]+"teen" : TEENS[n];
		} else {
			int n = number % 10;
			return TENS[number/10] +
				(n==0 ? "" : (" " + numberToWords(n)));
		}
	}

	public static void main(String[] args) {
		for (int i=0; i<100; i++) {
			System.out.println(i+" "+numberToWords(i));
		}
	}
}

written by objects \\ tags: , ,

Dec 03

Use the static valueOf() method

enum Colour
{
   red, green, blue
}

Colour red = Colour.valueOf("red");

written by objects \\ tags: , ,

Oct 13

You have a couple of choices, either:

  • Loop thru the array to convert each byte individually, or
  • Use the toString() method of the BigInteger class

// using a loop

StringBuilder sb =
   new StringBuilder(bytes.length * 2);
for (int i=0; i< bytes.length; i++)
{
    sb.append(String.format("%02x", bytes[i]));
}
String hex1 = sb.toString();

// using BigInteger

BigInteger bi = new BigInteger(bytes);
String hex2 = bi.toString(16); 

If you are dealing with large byte arrays or performance is an issue then you should have a read of “Converting large byte array to binary string”.

written by objects \\ tags: , , , ,