Solved

Convert Roman Numbers to Decimal Numbers

Posted on 2001-07-23
20
745 Views
Last Modified: 2010-08-05
Im new at using Java and I'm currently doing a project, part of which is to convert inputted  roman number to decimal numeral. Maybe someone can help me on this one. I badly needed it ASAP. Thanks in advance.
0
Comment
Question by:macjacinto
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 9
  • 2
20 Comments
 
LVL 1

Expert Comment

by:poluru
ID: 6307738
see the below program

/**
    * convert integer into Roman Numerals.
    * e.g. -12345 -> "minus MMMMMMMMMMMMCCCXLV"
    * Handles negative and positive integers
    * on range -Integer.MAX_VALUE .. Integer.MAX_VALUE;
    * It cannot handle Integer.MIN_VALUE;
    */
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class Roman
{

   public static String inWords( long num )
   {
      if ( num < 0 ) return "The Romans had no negative numbers.";
      if ( num == 0 ) return "The Romans had no zero.";
      if ( num > 100000 ) return "too unwieldy for Roman numerals";
      String s = "";
      // Work least significant digit to most, right to left.
      // until high order part is all 0s.
      for ( int i=0; num>0; i++ )
      {
         int remdr = (int)(num % divisor[i]);
         num = num / divisor[i];
         StringBuffer t;
         if ( i == 3 )
         {
            /* M is as big as it gets, just repeat */
            t = new StringBuffer(remdr);

            for ( int j=0; j<remdr; j++ )
            {
               t.append(unitLetter[i]);
            }
         }
         else
         {
            t = new StringBuffer(3);

            switch ( remdr )
            {
               
               case 0: break;

               case 1:
                  t.append(unitLetter[i]);
                  break;

               case 2:
                  t.append(unitLetter[i]);
                  t.append(unitLetter[i]);
                  break;

               case 3:
                  t.append(unitLetter[i]);
                  t.append(unitLetter[i]);
                  t.append(unitLetter[i]);
                  break;

               case 4:
                  t.append(unitLetter[i]);
                  t.append(fiveLetter[i]);
                  break;

               case 5:
                  t.append(fiveLetter[i]);
                  break;

               case 6:
                  t.append(fiveLetter[i]);
                  t.append(unitLetter[i]);
                  break;

               case 7:
                  t.append(fiveLetter[i]);
                  t.append(unitLetter[i]);
                  t.append(unitLetter[i]);
                  break;

               case 8:
                  t.append(fiveLetter[i]);
                  t.append(unitLetter[i]);
                  t.append(unitLetter[i]);
                  t.append(unitLetter[i]);

                  break;

               case 9:
                  t.append(unitLetter[i]);
                  t.append(unitLetter[i+1]);
                  break;

            } // end switch
         } // end else
         s = t + s;
      } // end for
      return s;
   } // end inWords

   public String toWords (long num)
   {
      return Roman.inWords(num);
   }

   private static final char[] unitLetter =  {
      'I', 'X', 'C', 'M'};

   private static final char[] fiveLetter =  {
      'V', 'L', 'D'};

   private static final int[] divisor = {
      /* How many of this group is needed to form one of the
succeeding group. */
      /* 1 10 100 1000 */
      10, 10, 10, 1000000};

   /**
    * test harness
    */
   public static void main (String[] args)
   {
             try
             {
                System.out.print("Enter aa Integer :");
                System.out.println(new Roman().toWords(Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine())));
           }
           catch(Exception e)
           {
                System.out.println(e);
           }
   } // end main
} // end Roman

0
 

Author Comment

by:macjacinto
ID: 6307824
sorry but i edited the question. it should have been roman numerals to decimal. thanks!
0
 
LVL 1

Expert Comment

by:poluru
ID: 6308173
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class todecimal
{
     public static void main(String args[]) throws Exception
     {
               while(true)
               {
                    System.out.print("Enter Roman Value to convert to Decimal : ");
                    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                    System.out.println(getDecimal(br.readLine()));

               }
     }

     public static long getMultiplier(char c)
     {
          switch(c)
          {
               case 'I' :
                              return 1;
                              //break;

               case 'V' :
                              return 5;
                              //break;

               case 'X' :
                              return 10;
                              //break;

               case 'L' :
                              return 50;
                              //break;

               case 'C' :
                              return 100;
                              //break;

               case 'D' :
                              return 500;
                              //break;
               case 'M' :
                              return 1000;
                              //break;
          };
          return -999;
     }

     public static long getDecimal(String str)
     {
          char ch[]=str.toCharArray();
          int len=ch.length;
          long sum=0l;
          long temp=0;
          boolean first=true;
          for(int i=len-1;i>=0;i--)
          {
               if(i==0 && first )
               {
                    sum+=getMultiplier(ch[i]);
                    System.out.println(sum);
                    break;
               }
               else if(i==0 && !first)
               {
                    sum-=getMultiplier(ch[i]);
                    System.out.println(sum);
                    break;
               }
               if(first && getMultiplier(ch[i])<=getMultiplier(ch[i-1]))
               {
                    sum+=getMultiplier(ch[i]);
               }
               else if(first && getMultiplier(ch[i])>getMultiplier(ch[i-1]))
               {
                         sum+=getMultiplier(ch[i]);
                         temp=getMultiplier(ch[i]);
                         first=false;

               }
               else if(!first && temp>getMultiplier(ch[i]))
               {
                    sum-=getMultiplier(ch[i]);
               }
               else
               {
                    sum+=getMultiplier(ch[i]);
                    temp=0;
                    first=true;
               }
          }
          return sum;
     }

     
}
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:macjacinto
ID: 6309189
im not yet able to to compile the code bec. my pc is having a little problem...does it accept invalid inputs like space, empty strings, digits and other characters other than the 7 mentioned above?? and and also what is the maximum number of roman numeral to be inputted?? thanks again in advance.
0
 

Author Comment

by:macjacinto
ID: 6310784
anyone??
0
 

Author Comment

by:macjacinto
ID: 6310950
anyone??
0
 
LVL 1

Expert Comment

by:poluru
ID: 6311010
No I Haven't checked all those things. U can just Validate them b4 passing it to the method.
0
 

Author Comment

by:macjacinto
ID: 6311308
anyone??
0
 

Author Comment

by:macjacinto
ID: 6311529
what's the function to check the number of characters in a string like the function len in vb? what should be added to the code so that it asks the user if he wants to exit, and exits if he presses y (yes).


i already compiled and run the code, it shows the answer twice, what should be done there??


pls reply ASAP! i really need this badly as soon as possible! thanks!
0
 
LVL 1

Expert Comment

by:poluru
ID: 6311659
0
 
LVL 1

Expert Comment

by:poluru
ID: 6311664
0
 
LVL 1

Expert Comment

by:poluru
ID: 6311666
0
 
LVL 1

Expert Comment

by:poluru
ID: 6311671
0
 

Author Comment

by:macjacinto
ID: 6311690
what do u mean no text??

anyone else who has an idea about this??

please, please, please!
0
 
LVL 1

Expert Comment

by:poluru
ID: 6311691
0
 
LVL 1

Expert Comment

by:poluru
ID: 6311697
iam not able to add my solution...every time i add my comment its showing no text and giving Error-2....
u can delete this qstn and add a new qstn so that i can add my comment....
0
 

Author Comment

by:macjacinto
ID: 6311703
what do u mean no text??

anyone else who has an idea about this??

please, please, please!
0
 

Author Comment

by:macjacinto
ID: 6311707
poloru suggested that i delete and repost it bec. he's having problems adding comments to it.
0
 
LVL 1

Accepted Solution

by:
Moondancer earned 0 total points
ID: 6351601
Rather than delete this, to maintain the information already provided, I have refunded your points so you can post new, and will move this to the PAQ to maintain an audit trail.

Thank you,
Moondancer
Community Support Moderator @ Experts Exchange
0
 
LVL 1

Expert Comment

by:Moondancer
ID: 6351603
Incidentally, for the "no text" problem, this question may be helpful as an interim solution, it posts some workarounds, until Engineering can resolve this intermittent problem:

http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20157348

Moondancer
Community Support Moderator @ Experts Exchange
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses

631 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question