Results 1 to 12 of 12
  1. #1
    arnelcolar's Avatar
    arnelcolar is offline Member
    Join Date
    Jul 2009
    Posts
    23
    Rep Power
    0

    Default Shorter code: Spell Out Numbers

    Hi I'm making a code to spell out a number from 0 to 199. Can you check this out:

    Java Code:
    import javax.swing.*;
    public class Say {
    
        static String ones[] = {" ","one","two","three","four","five","six","seven","eight","nine"};
        static String teen[] = {
            "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","ninteen"
    
        };
    
        static String tens[] = {
            " ","ten","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"};
    
        public static void main(String args[]) {
          int num =Integer.parseInt(JOptionPane.showInputDialog("Enter a number from 0-199"));
          
          int hundred = num/100; //=1.28
          int rem = num % 100;
          int ten = rem / 10;
            int one =rem % 10;
          if (hundred == 0) {
            System.out.println(tens[ten] + " " + ones[one]);
          }
            else if(rem == 0) {
            System.out.println(ones[hundred] + " hundred");
             }
            else{
            
                if ((rem >=10) && (rem <= 19)) {
                System.out.println(ones[hundred] + " hundred" + " " + teen[one]);
                } else {
                System.out.println(ones[hundred] + " hundred" + " " + tens[ten] + " " + ones[one]);}
                }
            
    }
    }
    Is there any possible way to make it shorter? Because my plan is to read numbers until a million.
    Are there any mistake in the code or some other ways to make it cleaner?

    Thank you.

  2. #2
    arnelcolar's Avatar
    arnelcolar is offline Member
    Join Date
    Jul 2009
    Posts
    23
    Rep Power
    0

    Default

    never mind the comment //1.28 I was simulating and I forgot to remove it. :)

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    For any number abcdefghi you basically spell it as abc million, def thousand, ghi. Note that those three parts are spelled using the same method. That leaves the task of spelling numbers such as abc; they are spelled as a hundred bc. A bit of recursion comes in handy here.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    arnelcolar's Avatar
    arnelcolar is offline Member
    Join Date
    Jul 2009
    Posts
    23
    Rep Power
    0

    Default

    Ok... I didn't quite get the idea. :p How about making it Object Oriented? Or will I just waste my time doing so.. ?

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by arnelcolar View Post
    Ok... I didn't quite get the idea. :p How about making it Object Oriented? Or will I just waste my time doing so.. ?
    There's not much to make 'object oriented' here; it's just one method; I'd add it to a simple utility class (just static methods). This is how I'd do it; study it and see if you'll understand:

    Java Code:
    public class Words {
    	
    	private static final String[] simple= { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
    											"ten", "evelen", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
    											"eightteen", "nineteen" };
    	
    	private static final String[] tens= { null, null, "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety" };
    	
    	public static String say(int number) { return say(number, true); }
    
    	private static String say(int number, boolean sayZero) {
    		
    		if (number < 0)				return "minus "+say(-number, sayZero);
    		
    		if (number == 0)			return sayZero?simple[number]:"";
    
    		if (number < 20) 			return simple[number];
    		
    		if (number < 100)			return tens[number/10]+say(number%10, false);
    	
    		if (number < 1000) 			return say(number/100, false)+"hundred"+say(number%100, false);
    
    		if (number < 1000000) 		return say(number/1000, false)+"thousand "+say(number%1000, false);
    
    		if (number < 1000000000)	return say(number/1000000, false)+"million "+say(number%1000000, false);
    		
    		return say(number/1000000000, false)+"billion "+say(number%1000000000, false);
    	}
    	
    	public static void main(String[] args) {
    		
    		System.out.println(say(1234));
    		System.out.println(say(1234567894));
    		System.out.println(say(1000));
    		System.out.println(say(-321));
    		System.out.println(say(-Integer.MAX_VALUE));
    	}
    }
    This class also contains a little main( ... ) method that tests the stuff. It can pronounce all integers (except Integer.MIN_VALUE); adjust it if you want to be able to handle longs (trillions, quadrillions etc.)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    arnelcolar's Avatar
    arnelcolar is offline Member
    Join Date
    Jul 2009
    Posts
    23
    Rep Power
    0

    Default

    Hey thanks! Just what I need. I'll study this one and get back here as soon as I'm done.

  7. #7
    Mitra VS is offline Member
    Join Date
    Feb 2011
    Posts
    1
    Rep Power
    0

    Default

    The code that has been posted is working well for all numbers except for those numbers starting with zero. How to eliminate the starting zero's and then spell out the number?

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Mitra VS View Post
    The code that has been posted is working well for all numbers except for those numbers starting with zero. How to eliminate the starting zero's and then spell out the number?
    No integer starts with a zero except zero.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    The code that has been posted is working well for all numbers except for those numbers starting with zero.

    The OP's code worked on a variable num which was an int. In Jos' code say() took an int argument. Things of type int don't "start with" anything: instances of String do.

    For instance what does the numeric quantity commonly held to be The Answer start with? 6 because its 6x7? X for an ancient roman? *?

    Only once you write it down as a String does it have a start or an end or length or a base...

    [Edit]

    One place where you would write down what you wanted the value of an int to be is in Java source code. What number are you using when you say

    Java Code:
    int ans = 052;

    in a piece of code? See if the code posted doesn't give the correct (merkin) English for that number.
    Last edited by pbrockway2; 02-23-2011 at 09:52 AM.

  10. #10
    Jodokus's Avatar
    Jodokus is offline Senior Member
    Join Date
    Jan 2011
    Location
    Amsterdam, the Netherlands
    Posts
    230
    Rep Power
    4

    Default

    I don't think Java is up to this ominous task. I'ld do it in VBA.

    Java Code:
    Option Explicit
    '=========================================================================
    Public Sub GetalNaarTekst()
    Dim strTitel As String
    Dim strVraag As String
    Dim strDefault As String
    Dim strAntwoord As String
    Dim intAntwoord As Long
    Dim strResult As String
    Dim doorgaan As Boolean
    strTitel = "Getal naar tekst"
    strVraag = "Geef een getal:"
    strDefault = ""
    doorgaan = True
    While doorgaan
        strAntwoord = InputBox(strVraag, strTitel, strDefault)
        If strAntwoord = "" Then
            doorgaan = False
        Else
            intAntwoord = Val(strAntwoord)
            strResult = fnGetal(intAntwoord)
            If strResult <> "" Then
                MsgBox "Invoer: " + Str(intAntwoord) + vbCrLf + _
                "De waarde is:" + vbCrLf + _
                strResult, vbInformation, "Het juiste antwoord"
            End If
        End If
    Wend
    End Sub
    '=========================================================================
    Private Function fnGetal(ByVal intGetal As Long) As String
    Dim strUitvoer As String
    
    'Domein----------------------------------------------
    'Alleen gehele getallen van -1.000.000 t/m 1.000.000
    If intGetal < -1000000 Or intGetal > 1000000 Then
        MsgBox "Verkeerd getal: " + Str(intGetal) + vbCrLf + _
        "(Alleen getallen van -1000000 t/m 1.000.000)", vbExclamation, "Verkeerde invoer"
        Exit Function
    End If
    'Negatief--------------------------------------------
    If intGetal < 0 Then
        strUitvoer = "min "
        intGetal = Abs(intGetal)
    End If
    'Nul en grenswaarde----------------------------------
    If intGetal = 0 Then
        fnGetal = "nul"
        Exit Function
    ElseIf intGetal = 1000000 Then
        strUitvoer = strUitvoer + "een " + Getaltekst(1000000)
        fnGetal = strUitvoer
        Exit Function
    End If
    'strUitvoer = strUitvoer + EenTotHonderd(intGetal) 'Voorlopig. Stapgewijs ophogen
    'strUitvoer = strUitvoer + EenTotTienduizend(intGetal) 'Voorlopig. Stapgewijs ophogen
    strUitvoer = strUitvoer + EenTotEenMiljoen(intGetal) 'Voorlopig. Stapgewijs ophogen
    fnGetal = strUitvoer
    End Function 'fnGetal
    '=========================================================================
    Private Function EenTotEenMiljoen(intGetal As Long) As String
    Dim intDuizenden As Long
    Dim intRest As Long
    Dim strUitvoer As String
    On Error GoTo fout
        If intGetal >= 1000000 Then
            Err.Raise 1111
        End If
    If intGetal < 10000 Then
        strUitvoer = EenTotTienduizend(intGetal)
    Else
        intDuizenden = intGetal \ 1000
                strUitvoer = strUitvoer + EenTotTienduizend(intDuizenden) + Getaltekst(1000)
        intRest = intGetal - (intDuizenden * 1000)
        If intRest <> 0 Then
            strUitvoer = strUitvoer + EenTotTienduizend(intRest)
        End If
    End If
    EenTotEenMiljoen = strUitvoer
    Exit Function
    fout:
        MsgBox "Te grote invoer getal: " + Str(intGetal), vbExclamation, "Programmeerfout in EenTotEenMiljoen"
    End Function
    '=========================================================================
    Private Function EenTotTienduizend(intGetal As Long) As String
    Dim intHonderden As Long
    Dim intRest As Long
    Dim strUitvoer As String
    On Error GoTo fout
        If intGetal >= 10000 Then
            Err.Raise 1111
        End If
        If intGetal < 100 Then
            strUitvoer = EenTotHonderd(intGetal)
        Else
            'Onder de 10.000. Duizend- en honderdtallen:
            '(Ik wil achtenachtighonderd, niet achtduizendachthonderd)
            intHonderden = intGetal \ 100
            If intHonderden Mod 10 = 0 Then   'duizendtallen
                If intHonderden \ 10 = 0 Then 'minder dan duizend
                    'niets
                ElseIf intHonderden \ 10 = 1 Then 'duizend
                    strUitvoer = strUitvoer + Getaltekst(1000)
                Else
                    strUitvoer = strUitvoer + EenTotHonderd(intHonderden \ 10) + Getaltekst(1000)
                End If
            Else
                If intHonderden = 1 Then  'honderd
                    strUitvoer = strUitvoer + Getaltekst(100)
                Else
                    strUitvoer = strUitvoer + EenTotHonderd(intHonderden) + Getaltekst(100)
                End If
            End If
            intRest = intGetal - (intHonderden * 100)
            'Het deel onder de honderd--------------------------
            If intRest <> 0 Then
                    strUitvoer = strUitvoer + EenTotHonderd(intRest)
            End If
        End If
    EenTotTienduizend = strUitvoer
    Exit Function
    fout:
        MsgBox "Te grote invoer getal: " + Str(intGetal), vbExclamation, "Programmeerfout in EenTotTienduizend"
    End Function
    '=========================================================================
    Private Function EenTotHonderd(intGetal As Long) As String
    Dim intTientallen As Long
    Dim intCijfers As Long
    Dim strUitvoer As String
    On Error GoTo fout
        If intGetal >= 100 Then
            Err.Raise 1111
        End If
        If intGetal <= 20 Then
            strUitvoer = Getaltekst(intGetal)
        Else
            intTientallen = intGetal \ 10
            intCijfers = intGetal - (intTientallen * 10)
            If intCijfers <> 0 Then
                If Right(Getaltekst(intCijfers), 1) = "e" Then
                    strUitvoer = Getaltekst(intCijfers) + "Žn"
                Else
                    strUitvoer = Getaltekst(intCijfers) + "en"
                End If
            End If
            strUitvoer = strUitvoer + Getaltekst(intTientallen * 10)
        End If
    EenTotHonderd = strUitvoer
    Exit Function
    fout:
        MsgBox "Te grote invoer getal: " + Str(intGetal), vbExclamation, "Programmeerfout in EenTotHonderd"
    End Function
    '=========================================================================
    Private Function Getaltekst(intGetal As Long) As String
    'Geeft tekst voor de basisgetallen
    Dim strUitvoer As String
    
    On Error GoTo fout
    Select Case intGetal
        Case 0
            strUitvoer = "nul"
        Case 1
            strUitvoer = "een"
        Case 2
            strUitvoer = "twee"
        Case 3
            strUitvoer = "drie"
        Case 4
            strUitvoer = "vier"
        Case 5
            strUitvoer = "vijf"
        Case 6
            strUitvoer = "zes"
        Case 7
            strUitvoer = "zeven"
        Case 8
            strUitvoer = "acht"
        Case 9
            strUitvoer = "negen"
        Case 10
            strUitvoer = "tien"
        Case 11
            strUitvoer = "elf"
        Case 12
            strUitvoer = "twaalf"
        Case 13
            strUitvoer = "dertien"
        Case 14
            strUitvoer = "veertien"
        Case 15
            strUitvoer = "vijftien"
        Case 16
            strUitvoer = "zestien"
        Case 17
            strUitvoer = "zeventien"
        Case 18
            strUitvoer = "achttien"
        Case 19
            strUitvoer = "negentien"
        Case 20
            strUitvoer = "twintig"
        Case 30
            strUitvoer = "dertig"
        Case 40
            strUitvoer = "veertig"
        Case 50
            strUitvoer = "vijftig"
        Case 60
            strUitvoer = "zestig"
        Case 70
            strUitvoer = "zeventig"
        Case 80
            strUitvoer = "tachtig"
        Case 90
            strUitvoer = "negentig"
        Case 100
            strUitvoer = "honderd"
        Case 1000
            strUitvoer = "duizend"
        Case 1000000
            strUitvoer = "miljoen"
        Case Else
        Err.Raise 1111
    End Select
    Getaltekst = strUitvoer
    Exit Function
    fout:
        MsgBox "Onbekend getal: " + Str(intGetal), vbExclamation, "Fout in Getaltekst"
    End Function 'Getaltekst

  11. #11
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Jodokus View Post
    I don't think Java is up to this ominous task. I'ld do it in VBA.
    Sure and reply #5 is just a figment of my imagination. VBA rules and Java sucks.

    kind regards,

    Jos ;-)
    cenosillicaphobia: the fear for an empty beer glass

  12. #12
    arnelcolar's Avatar
    arnelcolar is offline Member
    Join Date
    Jul 2009
    Posts
    23
    Rep Power
    0

    Default

    Thank you all for helping. I figured it out. (I just read it today after furious days of work)

    Thanks to JosAH for that code you shared. I'll reuse it and make a user input a number.

Similar Threads

  1. Spell Checker in Swing
    By dhaivat in forum New To Java
    Replies: 2
    Last Post: 07-01-2010, 06:08 PM
  2. Help with my code to find MinOfAll numbers
    By May.ver.rick in forum New To Java
    Replies: 9
    Last Post: 04-20-2010, 05:46 AM
  3. How to Spell out numbers?
    By syntrax in forum New To Java
    Replies: 5
    Last Post: 10-22-2009, 04:34 PM
  4. How do I make ImageIcon strings shorter.
    By Singing Boyo in forum New To Java
    Replies: 7
    Last Post: 03-10-2009, 10:29 AM
  5. spell check
    By kazitula in forum Java Applets
    Replies: 2
    Last Post: 12-20-2007, 12:37 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •