Feb 05

The Arrays class has a set of helper toString methods for converting an array to a string representation.

String representation = Arrays.toString(array);

This will work for all array types. For Objects it uses the toString() method of the type to convert array elements.

If you need more control how the array is represented then you will need to implement the conversion yourself using a loop.

written by objects \\ tags: , , ,

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: , ,

Jan 29

The fill() method in the Arrays class is useful for creating string filled with a certain character.

// create a buffer of 9 characters

char[] fill = new char[9];

// Fill the buffer with all '0's

Arrays.fill(fill, '0');

// Create string using the buffer

String zeroes = new String(fill);

// zeroes string now contains "000000000"

written by objects \\ tags: , , , ,