Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

can anyone help me shorten this JAVA program ?


newbee's Avatar
Member
0 0

I didn't use a Scanner class or a BufferedReader


starofale's Avatar
Member
0 0

Firstly, does that program run for you? It doesn't for me (Openjdk 1.6.0_24). The "main(int i)" is the problem on my computer.

Secondly, your program misses out some numbers (0, 100, 1000, 100000) and I get "ArrayIndexOutOfBoundsException" for large numbers.


newbee's Avatar
Member
0 0

thanks for the missing nos. , i fixed them , and as for the working of the program , it works fine for me , as i use BlueJ platform .

markuppublic static void main(int n)

is just for taking an integer 'n' as input from the user . you can try inserting a scanner class to take the no. as input .

and as for the larger nos. not working , this converter is for the indian no. system , 1 lakh means 100 thousands , and 1 crore = 100 lakhs = 10 million

as you can see that i commented , enter a no. less that 1 crore .


Arabian's Avatar
Member
0 0

There are many ways you can shorten this program. Take an input number and parse it toString(), keeping track of the length, then build your return value by splitting the string into it's constituent parts.

You're almost there, but you're not using what's available to you in Java's API.


newbee's Avatar
Member
0 0

thanks


ellipsis's Avatar
...
0 -1

newbee wrote: hello everyone , can anyone please help me to shorten this JAVA program ?

http://www.hellboundhackers.org/code/number-to-word-converter-2039_.html

p.s I'm not looking for ternary operators or an array to store the suffixes

If you mean shortening by lines, there are a few things you can do.

int x = (int)a/1000;
dis = dis + convert(x) + " thousand";

can be

dis = dis + convert((int)a/1000)) + " thousand";
System.out.println("input : " + i);
System.out.println("Output : " + dis);

can be

System.out.println("input : " + i + "\r\nOutput : " + dis);
if(n < 10 && n > 0 && flag == 0)
{
    out += " " + ones[n-1];
}

can be

if (n < 10 && n > 0 && flag == 0)
    out += " " + ones[n - 1];

Other than that, the code is as short as it can get.


chess_rock's Avatar
Member
0 0

I don't know if that is correct since i haven't tried to either compile or run it. Did everything on my notepad, so if there is any mistake, i'm sorry. I tried to shorten it as much as possible in the number of lines, and it ended up like this:

public class word_converter_fn
{
    public static String convert(int n) // this function converts numbers from 1 to 99 into words
    {
        String out = "";
	int flag = 0;
        String tens[] = {"ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
        String elevens[] = {"eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
        String ones[] = {"one","two","three","four","five","six","seven","eight","nine"};

        if (n >= 10)
        {
            if(n < 20 && n > 10)
            {
                out += " " + elevens[(n%10)-1];
                flag = 1;
            }
            else
            {
                out += " " + tens[(n/10)-1];
                n %= 10;
            }
        }

        return (n < 10 && n > 0 && flag == 0) ? out + " " + ones[n-1] : out;
    }

    /* enter no. to be written in words (less than 1 crore)*/
    public static void main(int i) // this function takes input from user , sends it to convert() and adds suffixes like lakh, thousand ,etc.
    {
        int a = i;
        String dis = "";

        if(a == 0)
	{
            dis = "zero";
       	}
	else
	{
            if(a > 100000)
            {
                dis = dis + convert((int)a/100000) + " lakh";
                a %= 100000;
       	    }
            if(a >= 1000 && a < 100000)
            {
                dis = dis + convert((int)a/1000) + " thousand";
                a %= 1000;
            }
            if(a >= 100 && a < 1000)
            {
                dis = dis + convert((int)a/100) + " hundred";
                a %= 100;
            }
	}

        dis += (a >= 0 && a < 100) ? (dis + convert(a)) : "";
        System.out.println("input : " + i + "\r\nOutput : " + dis.trim());
    }
}

Most of the code lines' shortening is due to ternary operators :)

edit: did put the trim on the wrong place, now i changed it


newbee's Avatar
Member
0 0

I appreciate your help.


ellipsis's Avatar
...
0 -1

newbee wrote: I appreciate your help.

public class word_converter_fn {
    public static String convert(int n) {   // this function converts numbers from 1 to 99 into words
        String out = ""; int flag = 0;
        String tens[] = {"ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
        String elevens[] = {"eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
        String ones[] = {"one","two","three","four","five","six","seven","eight","nine"};
        
	if (n >= 10) {
            if(n < 20 && n > 10) {
                out += " " + elevens[(n%10)-1];
                flag = 1;
            } else {
                out += " " + tens[(n/10)-1];
                n = n%10;
            }
        } else if(n < 10 && n > 0 && flag == 0)
            out += " " + ones[n-1];

        return out;
    }
    /* enter no. to be written in words (less than 1 crore)*/
    public static void main(int i) {  // this function takes input from user, sends it to convert() and adds suffixes like lakh, thousand ,etc.
        int a = i; String dis = "";

        if (a == 0)
            dis = "zero";  
        else if (a > 100000) {
            dis = dis + convert((int)a / 100000) + " lakh";
            a = a % 100000;
        } else if (a >= 1000 && a < 100000) {
            dis = dis + convert((int)a / 1000) + " thousand";
            a = a % 1000;
        } else if (a >= 100 && a < 1000) {
            dis = dis + convert((int)a / 100) + " hundred";
            a = a % 100;
        } else if (a >= 0 && a < 100)
           dis = dis + convert(a);
 
        dis = dis.trim();

        System.out.println("input : " + i + "\r\nOutput : " + dis);
    }
}

Merely cosmetic.


newbee's Avatar
Member
0 0

i meant that i appreciated the fact that they tried to help me .


elmiguel's Avatar
Member
2,795 1

Just thought I play around with this program and noticed flaw

Had to arrange the main since I use PSPad to run java

  public static void main(String args[]) { 
...
    for(String arg : args){
    	int i = Integer.parseInt(arg.toString());

...code...

after running the program in the console…


C:\wamp\www\hbh\javaHelp>java word_converter_fn 1 45 17
input : 1
Output : one
input : 45
Output : forty
input : 17
Output : seventeen

C:\wamp\www\hbh\javaHelp>

You will notice that the second parameter did not parse correctly

C:\wamp\www\hbh\javaHelp>java word_converter_fn 45
input : 45
Output : forty

C:\wamp\www\hbh\javaHelp>

Now unless you only intended to output the group in which the number belongs, this is not 100%, if you did only intend for this, then ok.

As for even more shortening, this:

dis = dis + convert((int)a / 100000) + " lakh"; 

can be this:

dis += convert((int)a / 100000) + " lakh"; 

no need to recreate the variable.

this:

dis = dis.trim(); 
System.out.println("input : " + i + "\r\nOutput : " + dis);

can be this:

System.out.println("input : " + i + "\r\nOutput : " + dis.trim());

There is more but I will rewrite it and then post it back.

Please note that there are as many ways to write a program as there are programmers to look at it. These suggestions are only my opinion.


newbee's Avatar
Member
0 0

it works perfectly fine on my PC (i'm using BlueJ) , for input 45 it gives output "forty five" .

and thanks for the help


ellipsis's Avatar
...
0 -1

newbee wrote: it works perfectly fine on my PC (i'm using BlueJ) , for input 45 it gives output "forty five" .

and thanks for the help

Blue J is the worst Java "IDE" ever. Just saying. :right:


Arabian's Avatar
Member
0 0

if you're going to use Java, just use Eclipse. There's really no sense in using anything else for it :/


ellipsis's Avatar
...
0 -1

Arabian wrote: if you're going to use Java, just use Eclipse. There's really no sense in using anything else for it :/

It's a tough choice between Eclipse or NetBeans. Personally, NetBeans has everything you need. It's possibly the best Java IDE on the interweb.


newbee's Avatar
Member
0 0

i have to use bluej , coz our indian education system recognizes only that as a JAVA IDE .


elmiguel's Avatar
Member
2,795 1

Still working on the new program; fun little project. Enhancing the program to produce precise output. Working with a colleague to make it more efficient. Complete rewrite, but I think you will enjoy the result.

BlueJ is more a CType (Using this lightly; meaning that the main can accept any data type) Java IDE it is not a real production environment. If you are going to explore more of Java, I suggest some IDEs that have been already mention: Eclipse and/or NetBeans. There several more out there that link into the Java JDK and are good for specifics. I myself use PSPad, a well diverse Text Editor that has the capability to run compilers. Has great syntax highlighters, lightweight, and customizable.

** BlueJ does not recognize Java standards :

Java Standard main: public static void main(String[] args){…}

BlueJ main method:

public static void main(<T> var){…}

Although this is great for cross language support, it does not follow traditional Java standard. This software is mainly used for introductory use to get students/beginners a generic feel of Java and OOP.

If you read over the why section on bluej.org: number 4, you will understand why some educational institutions use BlueJ as a introductory to Java.

Java is a reasonably clean language, but by no means free of problems for introductory teaching. For teachers, it is important to know those problems and to have a way to deal with them. Two of the problems most often reported in the literature (for example in [1] and [4]) are:

problems with the main function
problems with text I/O

The main function: The main function has to be written with the signature

public static void main (String[] args)

This causes several problems. Firstly, several concepts are used here which cannot be explained at this stage (static functions, arrays, void return types). So teachers have to use some hand-waiving ("just believe me and write it like this") and students feel frustrated. Secondly, this has nothing to do with object-orientation! The main function does not logically belong to any object. Thus, students start off with seeing an exception rather than a good example of object-orientation.

I/O: Text I/O, especially input, is not simple and causes regular problems. In addition, it forces students to deal with exceptions at a very early stage.

BlueJ solves both of these problems!

Because objects can be created interactively, and methods can be called interactively, there is no need for a main function. Students can write classes and call their methods without a need to have a main. And because parameters can be passed to interactive method calls and results are displayed, there is no immediate need for I/O. Students can write and test very sophisticated code without the need for any I/O operations!

http://www.bluej.org/about/why.html

In the real world, traditional Java is 90% of time is used, if not more.


newbee's Avatar
Member
0 0

ok man i will definitely try out eclipse and netbeans


tuere816's Avatar
Member
0 0

newbee wrote: i have to use bluej , coz our indian education system recognizes only that as a JAVA IDE .

QUOTING OUT OF OP's context ,BUT, the fact remains that Mumbai university does accept Eclipse as an IDE at engineering level :)


ellipsis's Avatar
...
0 -1

tuere816 wrote: [quote]newbee wrote: i have to use bluej , coz our indian education system recognizes only that as a JAVA IDE .

QUOTING OUT OF OP's context ,BUT, the fact remains that Mumbai university does accept Eclipse as an IDE at engineering level :)[/quote]

Eclipse is an awesome IDE. I think they should at least accept NetBeans as an IDE…I mean…it is and integrated development environment…complete with drag&drop GUI development like visual studio. That sucks though.


newbee's Avatar
Member
0 0

that's mumbai university , at engineering level . i'm talking about secondary / sr. secondary level .

in other words , i can't use eclipse to clear my school finals or the ISC exams .

but i will give it a try .


newbee's Avatar
Member
0 0

netbeans doesn't work for me , i tried it and got confused by the interface .

i'll try out eclipse soon .


elmiguel's Avatar
Member
2,795 1

After many revisions and testing I believe me and my colleague have come up with a decent working revision to your program. It is not shorter but is pretty efficient (dealing with strings that is)

This will take up to 999 decillion (positive).

the code is below

this was done with NetBeans as the IDE

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package word_converter_fn;

/**
 *
 * @author elmiguel and selliser
 */
public class Word_converter_fn {
   private static String ones[]     = {&quot;one&quot;,&quot;two&quot;,&quot;three&quot;,&quot;four&quot;,&quot;five&quot;,&quot;six&quot;,&quot;seven&quot;,&quot;eight&quot;,&quot;nine&quot;}; 
   private static String elevens[]  = {&quot;ten&quot;,&quot;eleven&quot;,&quot;twelve&quot;,&quot;thirteen&quot;,&quot;fourteen&quot;,&quot;fifteen&quot;,&quot;sixteen&quot;,&quot;seventeen&quot;,&quot;eighteen&quot;,&quot;nineteen&quot;}; 
   private static String tens[]     = {&quot;twenty&quot;,&quot;thirty&quot;,&quot;forty&quot;,&quot;fifty&quot;,&quot;sixty&quot;,&quot;seventy&quot;,&quot;eighty&quot;,&quot;ninety&quot;};
   private static String decimalGrouping[] = {&quot;thousand&quot;, &quot;million&quot;, &quot;billion&quot;, &quot;trillion&quot;, &quot;quadrillion&quot;, &quot;sextillion&quot;, &quot;septillion&quot;, &quot;octillion&quot;,&quot;nonillion&quot;, &quot;decillion&quot;};   
   
   public static String calculateTriple(int number){
       //check for even group values (i.e. 1,000)
       if(number==0){
       return &quot;&quot;;
       }
      String tripleString=&quot;&quot;;
      int localCalc=number%100; 
      if (number&gt;99){
           tripleString+=convertOnes(number/100)+&quot; hundred &quot;;
       }
      //x Modulo 100 gives us the right two digits.
      //Check for Elevens first
      if(localCalc&lt;20 && localCalc&gt;=10){
          tripleString+=convertElevens(localCalc);
      }else{
          //not an eleven; calc tens then ones
          if(localCalc&gt;19){
           tripleString+=convertTens(localCalc)+&quot; &quot;;
          }
          //always calc ones
          tripleString+=convertOnes(localCalc%10);
      }
       return tripleString;
   }
   public static String calculateGroup(int number){
       return decimalGrouping[number];
   }
   public static String convertOnes(int number){
       if(number&gt;0){
        return ones[number-1];    
       }
       else{
           return &quot;&quot;;
       }
   }
   public static String convertElevens(int number){
       return elevens[(number%10)];
   }
   public static String convertTens(int number){
       return tens[number/10 -2];//-2 is the normal -1 offset plus
                                // an additoinal -1 for removing &quot;ten&quot;
   }

  public static String convert(String n) { 
    String out = &quot;&quot;;
    String tripleNum=&quot;&quot;;
    
    if (n.equals(&quot;0&quot;)){
        return &quot;zero&quot;;
    }//zero check
    //Zero pad the front of the string 
    while(n.length()%3!=0){

        n=&quot;0&quot;+n;
    }
    //First check for elevens becuase they don&#39;t follow
    //nomenclature rules
    int decimalGroupIndex=n.length()/3;
    for(int i=0;i&lt;n.length()/3;i++){        
        if(i&gt;0){
         out+= &quot; &quot; + decimalGrouping[(decimalGroupIndex-i)-1] + &quot; &quot;;
        }
        //Break the number into three-digit intervals.
        tripleNum=n.substring(i*3, (i*3)+3);
        out+= calculateTriple(Integer.parseInt(tripleNum));
    }//loop

      return out; 
      }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
          
            for(String arg : args){
                    System.out.println(&quot;input : &quot; + arg + &quot;&#92;r&#92;nOutput : &quot; + convert(arg).trim());
            }
    }
}


output:

run:
input : 958156398212756245978539894599436
Output : nine hundred fifty eight decillion one hundred fifty six nonillion three hundred ninety eight octillion two hundred twelve septillion seven hundred fifty six sextillion two hundred forty five quadrillion nine hundred seventy eight trillion five hundred thirty nine billion eight hundred ninety four million five hundred ninety nine thousand four hundred thirty six
BUILD SUCCESSFUL (total time: 0 seconds)


newbee's Avatar
Member
0 0

whoa man thanks for such a great program , although i'll need 3/4 hours to get hold of it . anyway thanks again .


elmiguel's Avatar
Member
2,795 1

No problem, submitted the code to the code bank and working on another revision. I think I can shorten it down some. When I am finished I will submit that as well since it will be a different approach.

Enjoy. B)


ghost's Avatar
0 0

%5bquote%5d%5bb%5dellipsis+wrote%3a%5b%2fb%5d%0a%5bquote%5d%5bb%5dtuere816+wrote%3a%5b%2fb%5d%0d%0a%5bquote%5d%5bb%5dnewbee+wrote%3a%5b%2fb%5d%0d%0ai+have+to+use+bluej+%2c+coz+our+indian+education+system+recognizes+only+that+as+a+JAVA+IDE+.+%5b%2fquote%5d%0d%0a%0d%0a%0d%0aQUOTING+OUT+OF+OP%26%2339%3bs+context+%2cBUT%2c+the+fact+remains+that+Mumbai+university+does+accept+Eclipse+as+an+IDE+at+engineering+level+%3a%29%5b%2fquote%5d%0d%0a%0d%0aEclipse+is+an+awesome+IDE.++I+think+they+should+at+least+accept+NetBeans+as+an+IDE…I+mean…it+is+and+integrated+development+environment…complete+with+drag%26drop+GUI+development+like+visual+studio.++That+sucks+though.++%5b%2fquote%5d