-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumberToWords.java
43 lines (36 loc) · 1.2 KB
/
NumberToWords.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Write a method called numberToWords with one int parameter named number.
// The method should print out the passed number using words for the digits.
// If the number is negative, print “Invalid Value”.
// Example Input/Output
// numberToWords(123)-> should print “One Two Three”.
// numberToWords(3456)-> should print “Three Four Five Six”.
// numberToWords(-7)-> should print “Invalid Value” since parameter is negative;
import java.util.*;
class NumberToWords
{
public static void numberToWords (int num)
{
if (num < 0)
{
System.out.println ("-1");
return;
}
int temp = num;
ArrayList < String > list = new ArrayList < String > ();
String arr[] ={ "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven","Eight", "Nine" };
while (temp != 0)
{
list.add (arr[temp % 10]);
temp = temp / 10;
}
for (int i = list.size () - 1; i >= 0; i--)
System.out.print (list.get (i) + " ");
System.out.println ();
}
public static void main (String[]args)
{
numberToWords (123);
numberToWords (3456);
numberToWords (-7);
}
}