Write a program that asks the user to enter an integer from 20 to 99 in numeric form. The program should output the equivalent number in words. For example, if an input of 58, the output is fifty eight
public class DigitsConverter {
public static void main(String[] args) {
boolean isValidNumber = false;
System.out.println("Enter number from 20 to 99: ");
while (!isValidNumber) {
int number = new Scanner(System.in).nextInt();
isValidNumber = numberInWords(number);
}
}
private static boolean numberInWords(int number) {
if (number < 20 || number > 99) {
System.out.println("** Error ** Number must be from 20 to 99, please re-enter: ");
return false;
}
StringBuilder sb = new StringBuilder();
int ones = number % 10;
int tens = number / 10 % 10;
sb.append(convertTensToWords(tens))
.append(" ")
.append(convertOnesToWords(ones));
System.out.println(sb);
return true;
}
private static String convertTensToWords(int number) {
switch (number) {
case 2:
return "twenty";
case 3:
return "thirty";
case 4:
return "forty";
case 5:
return "fifty";
case 6:
return "sixty";
case 7:
return "seventy";
case 8:
return "eighty";
case 9:
return "ninety";
default:
return null;
}
}
private static String convertOnesToWords(int number) {
switch (number) {
case 1:
return "one";
case 2:
return "two";
case 3:
return "three";
case 4:
return "four";
case 5:
return "five";
case 6:
return "six";
case 7:
return "seven";
case 8:
return "eight";
case 9:
return "nine";
default:
return null;
}
}
}
Comments
Leave a comment