Hi guys i'm trying to write a simple program using control structures to convert numbers to words but the program is becoming way too long. Is there a simpler way to write it? An example is, if a user inputs 123 the output should be one two three. I didn't complete it but here is a sample:
import java.util.Scanner;
public class Number10 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String num;
System.out.print("Enter a number and i'll convert it to words: ");
num = input.nextLine();
if((num.length()) == 1)
{
switch(num)
{
case "0":
{
System.out.print("Zero");
break;
}
case "1":
{
System.out.print("One");
break;
}
case "2":
{
System.out.print("Two");
break;
}
case "3":
{
System.out.print("Three");
break;
}
case "4":
{
System.out.print("Four");
break;
}
case "5":
{
System.out.print("Five");
break;
}
case "6":
{
System.out.print("Six");
break;
}
case "7":
{
System.out.print("Seven");
break;
}
case "8":
{
System.out.print("Eight");
break;
}
case "9":
{
System.out.print("Nine");
break;
}
default:
{
System.out.print("Please enter a number");
break;
}
}
}
else if((num.length()) == 2)
{
switch(num)
{
case "11":
{
System.out.print("One One");
break;
}
case "12":
{
System.out.print("One Two");
break;
}
case "13":
{
System.out.print("One Three");
break;
}
case "14":
{
System.out.print("One Four");
break;
}
case "15":
{
System.out.print("One Five");
break;
}
case "16":
{
System.out.print("One Six");
break;
}
case "17":
{
System.out.print("One Seven");
break;
}
case "18":
{
System.out.print("One Eight");
break;
}
case "19":
{
System.out.print("One Nine");
break;
}
case "20":
{
System.out.print("Two Zero");
break;
}
case "21":
{
System.out.print("Two One");
break;
}
case "22":
{
System.out.print("Two Two");
break;
}
case "23":
{
System.out.print("Two Three");
break;
}
case "24":
{
System.out.print("Two Four");
break;
}
default:
{
System.out.print("Please enter a number");
break;
}
}
}
else
{
System.out.print("Invalid number");
}
}
}
Please help me out. Thanks.