31.8k views
2 votes
Sometimes numbers are converted to words, like in a wedding invitation. So 23 becomes "twenty three". Write a method digitToWord() that takes a single digit number from 0-9 and returns that number's word: 0 is zero, 1 is one, 2 is two, etc (if the number is outside 0-9, return "error"). Write another method tensDigitToWord() that takes a single digit number from 2-9, and returns that number's word when it appears in the tens digit: 2 is twenty, 3 is thirty, etc. If the number is outside 2-9, return "error". Finally, write a method twoDigitNumToWords() that takes a two-digit number from 20-99 and returns that number in words. Your main program should get a user's integer, call twoDigitNumToWords(), and output the resulting string. If the input is 23, the output should be "twenty three".

1 Answer

5 votes

Final answer:

To solve this problem, we can create three separate methods: digitToWord(), tensDigitToWord(), and twoDigitNumToWords(). The digitToWord() method takes a single digit number from 0-9 and returns that number's word. The tensDigitToWord() method takes a single digit number from 2-9 and returns that number's word when it appears in the tens digit. The twoDigitNumToWords() method takes a two-digit number from 20-99 and returns that number in words.

Step-by-step explanation:

To solve this problem, we can create three separate methods: digitToWord(), tensDigitToWord(), and twoDigitNumToWords().

The digitToWord() method takes a single digit number from 0-9 and returns that number's word. We can use a switch statement to check the input number and return the corresponding word.

The tensDigitToWord() method takes a single digit number from 2-9 and returns that number's word when it appears in the tens digit. Again, we can use a switch statement to check the input number and return the corresponding word.

The twoDigitNumToWords() method takes a two-digit number from 20-99 and returns that number in words. We split the number into its tens and ones digits and call the tensDigitToWord() method to get the word for the tens digit, and then call the digitToWord() method to get the word for the ones digit.

Finally, in the main program, we can get the user's input integer, call the twoDigitNumToWords() method, and output the resulting string.

User Cathal
by
8.7k points