Learn how to convert number to words in Java with a simple example. This tutorial explains the logic, source code, and output for converting numbers from 1 to 99 into words.
Code Explanation (Step-by-Step)
- First, create a Scanner class object to accept input from the user.
- Use the sc.nextInt() method to read an integer value from the user and store it in the userNumber variable.
- In the first if condition, check whether the entered number is less than 1 or greater than 99. If it is, print “wrong number”.
- In the else if condition, check whether the number is between 1 and 19. If it is, print the corresponding word using the str2 array .
- In the second else if condition, check whether the number is between 20 and 99.
- Divide the number by 10 and store the result in the digit1 variable. This value represents the tens place of the number.
- Use digit1 as an index for the str1 array to get the word for the tens place (such as twenty, thirty, forty, etc.).
- Find the remainder by using the modulo (%) operator and store it in the digit2 variable. This value represents the ones place of the number.
- Use digit2 as an index for the str2 array to get the word for the ones place.
- Now, combine the values from both arrays and print the complete number in words.
import java.util.Scanner;
public class A {
public static void main(String[] args) {
int userNumber, digit1, digit2;
Scanner sc = new Scanner(System.in);
String str1[] = {
"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"
};
String str2[] = {
"", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen",
"eighteen", "nineteen"
};
System.out.println("Enter the user number between 1 to 99");
userNumber = sc.nextInt();
if ((userNumber < 1) || (userNumber > 99)) {
System.out.println("Wrong Number");
} else if ((userNumber >= 1) && (userNumber <= 19)) {
System.out.println("Number in words: " + str2[userNumber]);
} else {
digit1 = userNumber / 10;
digit2 = userNumber % 10;
System.out.println("Number in words: "
+ str1[digit1] + " " + str2[digit2]);
}
sc.close();
}
}
Output :-
Enter the user number between 1 to 99
56
print number to words :- fifty six
Validate the Number
import java.util.Scanner;
public class NumberValidation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number between 1 and 99:");
int userNumber = sc.nextInt();
String result = (userNumber >= 1 && userNumber <= 99)
? "Valid Number"
: "Wrong Number";
System.out.println(result);
sc.close();
}
}
Here are some Java-related programs that will help you understand Java concepts better: