Roman numeral to decimal

Hi:
can anyone give me a hint about how to convert a number entered in Roman numerals to decimal? The program should consist of a class, say Roman.

a) Store the number as a ROman numberal.

b) Convert and store the number into decimal.

c) Print the number as a ROman numberal or decimal numbers as requested by the user.
crystalfish0318Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sudhakar_koundinyaCommented:
I Suggest this code


//$Id: Roman.java,v 1.11 2001/01/07 15:12:00 benc Exp $
package benno.number;

import java.text.*;

/**
<p>
This NumberFormat converts long integers to and from Roman Numeral notation.
Once an instance has been created, the format and parse methods may be used
as defined in java.text.NumberFormat.
</p>

<p>
The
<a href="../benno/applets/RomanNumeralConverter.html">RomanNumeralConverter
applet</a> demonstrates the use of this class.
</p>

@see benno.applets.RomanNumeralConverter
@author Ben Clifford
@version $Revision: 1.11 $
*/

public class Roman extends NumberFormat
{


/** This method returns null. I have found no meaningful translation
    of floating point numbers to Roman numerals, however the NumberFormat
    method requires that it is implemented. Perhaps should just cast
    the double to a long and format accordingly.
*/

      public StringBuffer format(double n, StringBuffer a, FieldPosition p)
      {
            return null;
      }


/** This nested class is used to map Roman symbols onto their numerical
    values. Used in the Roman class.
    @see benno.applets.Roman
*/

      public static class SymTab
      {
            /** Roman symbol */
            char symbol;

            /** Numerical value */
            long value;

            /** Constructor to build a SymTab from supplied symbol and value
                @param s Roman symbol
                @param v Numerical value
   */
      public SymTab(char s, long v) { this.symbol=s; this.value=v; }
   };


/** This table maps individual Roman symbols onto their numerical
    values.<br>
    Unfortunately, JavaDoc JDK 1.1 does not create documentation
    for the inner class Roman.SymTab, so the reader
    cannot see the definition.
*/

            public static Roman.SymTab syms[]= {
               new Roman.SymTab('M',1000),
                  new Roman.SymTab('D',500),
               new Roman.SymTab('C',100),
               new Roman.SymTab('L',50),
               new Roman.SymTab('X',10),
               new Roman.SymTab('V',5),
               new Roman.SymTab('I',1)
            };


/** This method converts a Roman Numeral string to a long integer. It does
    not check that the string is in the correct format - for some incorrectly
    formatted numbers, i.e. iix, it will produce a number. For others,
    it will throw an exception.

    @param s string of Roman Numerals
            @param parsePosition the place to start parsing
    @return A Long object containing the parsed Roman numeral
*/

      public Number parse(String text, ParsePosition parsePosition)
      {

      String s = text.substring(parsePosition.getIndex());
                  
       long tot=0,max=0;
       char ch[]=s.toUpperCase().toCharArray();
      int i,p;
      for(p=ch.length-1;p>=0;p--)
      {
            for(i=0;i<syms.length;i++)
            {
                  if(syms[i].symbol==ch[p])
                  {
                        if(syms[i].value>=max)
                              tot+= (max = syms[i].value);
                        else
                              tot-= syms[i].value;
                  }
            }
      }

      // say that we parsed the whole string
      parsePosition.setIndex(s.length());
      return new Long(tot);
      }


/** This method converts a Roman Numeral string to a long integer. It does
    not check that the string is in the correct format - for some incorrectly
    formatted numbers, i.e. iix, it will produce a number. For others,
    it will throw an exception.

    @param s string of Roman Numerals
    @return The integer representation of the Numerals
*/

      public static long toLong(String s)
      {
            long tot=0,max=0;
            char ch[]=s.toUpperCase().toCharArray();
            int i,p;
            for(p=ch.length-1;p>=0;p--)
             {
                  for(i=0;i<syms.length;i++)
                  {
                        if(syms[i].symbol==ch[p])
                        {
                              if(syms[i].value>=max)
                                    tot+= (max = syms[i].value);
                              else
                                    tot-= syms[i].value;
                        }
                  }
            }
            return tot;
      };


/** This method converts the supplied long into capitalised Roman
    numerals.<br>
    BUG: the method does not take account of the
    <code>FieldPosition p</code> parameter.

    @param n The number to be converted into Roman numerals
    @param s The StringBuffer into which the output is to be placed.
    @return The StringBuffer s
*/

            public StringBuffer format(long n, StringBuffer s, FieldPosition p)
         {
                  int i;
                  while(n>0)
                  {
                        for(i=0;i<syms.length;i++)
                        {
                              if(syms[i].value<=n)
                              {
                                    int shift=i+(i%2);
                                    if( i>0 && shift<syms.length &&
                (syms[i-1].value-syms[shift].value) <= n )
                                    {
                                    s.append( syms[shift].symbol);
                                    s.append( syms[i-1].symbol);
                                    n= n - syms[i-1].value + syms[shift].value;

                                    i=-1;
                              }
                              else
                              {
                                    s.append(syms[i].symbol);
                                    n-=syms[i].value;
                                    i=-1;
                              }
                        }
                  }
            }
            return s;
      }


/** This method converts a long integer to capitalised Roman notation.

    @param n The integer to convert to Roman Numerals.
    @return A String object containing the Roman Numerals.

*/

   public static String toRoman(long n)
   {
         int i;
            String s;
      s="";
      while(n>0)
      {
                  for(i=0;i<syms.length;i++)
            {
                        if(syms[i].value<=n)
                        {
                              int shift=i+(i%2);
                              if( i>0 && shift<syms.length &&
                                   (syms[i-1].value-syms[shift].value) <= n )
                              {
                                    s= s+ syms[shift].symbol + syms[i-1].symbol;
                                    n= n - syms[i-1].value + syms[shift].value;

                                    i=-1;


                              }
                              else
                              {
                                    s+=syms[i].symbol;
                                    n-=syms[i].value;
                                    i=-1;
                              }
                        }
                  }
            }
            return s;
      }

}


and downloaded from http://www.hawaga.org.uk/java/benno/number/Roman.java
sudhakar_koundinyaCommented:
this  idea quite opposite to yours
sudhakar_koundinyaCommented:
Ignore my second comment.

It works for both.


import java.text.*;

public class Roman extends NumberFormat
{



      public StringBuffer format(double n, StringBuffer a, FieldPosition p)
      {
            return null;
      }



      public static class SymTab
      {
            /** Roman symbol */
            char symbol;

            /** Numerical value */
            long value;

            /** Constructor to build a SymTab from supplied symbol and value
                @param s Roman symbol
                @param v Numerical value
   */
      public SymTab(char s, long v) { this.symbol=s; this.value=v; }
   };


/** This table maps individual Roman symbols onto their numerical
    values.<br>
    Unfortunately, JavaDoc JDK 1.1 does not create documentation
    for the inner class Roman.SymTab, so the reader
    cannot see the definition.
*/

            public static Roman.SymTab syms[]= {
               new Roman.SymTab('M',1000),
                  new Roman.SymTab('D',500),
               new Roman.SymTab('C',100),
               new Roman.SymTab('L',50),
               new Roman.SymTab('X',10),
               new Roman.SymTab('V',5),
               new Roman.SymTab('I',1)
            };


/** This method converts a Roman Numeral string to a long integer. It does
    not check that the string is in the correct format - for some incorrectly
    formatted numbers, i.e. iix, it will produce a number. For others,
    it will throw an exception.

    @param s string of Roman Numerals
            @param parsePosition the place to start parsing
    @return A Long object containing the parsed Roman numeral
*/

      public Number parse(String text, ParsePosition parsePosition)
      {

      String s = text.substring(parsePosition.getIndex());
                  
       long tot=0,max=0;
       char ch[]=s.toUpperCase().toCharArray();
      int i,p;
      for(p=ch.length-1;p>=0;p--)
      {
            for(i=0;i<syms.length;i++)
            {
                  if(syms[i].symbol==ch[p])
                  {
                        if(syms[i].value>=max)
                              tot+= (max = syms[i].value);
                        else
                              tot-= syms[i].value;
                  }
            }
      }

      // say that we parsed the whole string
      parsePosition.setIndex(s.length());
      return new Long(tot);
      }


/** This method converts a Roman Numeral string to a long integer. It does
    not check that the string is in the correct format - for some incorrectly
    formatted numbers, i.e. iix, it will produce a number. For others,
    it will throw an exception.

    @param s string of Roman Numerals
    @return The integer representation of the Numerals
*/

      public static long toLong(String s)
      {
            long tot=0,max=0;
            char ch[]=s.toUpperCase().toCharArray();
            int i,p;
            for(p=ch.length-1;p>=0;p--)
             {
                  for(i=0;i<syms.length;i++)
                  {
                        if(syms[i].symbol==ch[p])
                        {
                              if(syms[i].value>=max)
                                    tot+= (max = syms[i].value);
                              else
                                    tot-= syms[i].value;
                        }
                  }
            }
            return tot;
      };


/** This method converts the supplied long into capitalised Roman
    numerals.<br>
    BUG: the method does not take account of the
    <code>FieldPosition p</code> parameter.

    @param n The number to be converted into Roman numerals
    @param s The StringBuffer into which the output is to be placed.
    @return The StringBuffer s
*/

            public StringBuffer format(long n, StringBuffer s, FieldPosition p)
         {
                  int i;
                  while(n>0)
                  {
                        for(i=0;i<syms.length;i++)
                        {
                              if(syms[i].value<=n)
                              {
                                    int shift=i+(i%2);
                                    if( i>0 && shift<syms.length &&
                (syms[i-1].value-syms[shift].value) <= n )
                                    {
                                    s.append( syms[shift].symbol);
                                    s.append( syms[i-1].symbol);
                                    n= n - syms[i-1].value + syms[shift].value;

                                    i=-1;
                              }
                              else
                              {
                                    s.append(syms[i].symbol);
                                    n-=syms[i].value;
                                    i=-1;
                              }
                        }
                  }
            }
            return s;
      }


/** This method converts a long integer to capitalised Roman notation.

    @param n The integer to convert to Roman Numerals.
    @return A String object containing the Roman Numerals.

*/

   public static String toRoman(long n)
   {
         int i;
            String s;
      s="";
      while(n>0)
      {
                  for(i=0;i<syms.length;i++)
            {
                        if(syms[i].value<=n)
                        {
                              int shift=i+(i%2);
                              if( i>0 && shift<syms.length &&
                                   (syms[i-1].value-syms[shift].value) <= n )
                              {
                                    s= s+ syms[shift].symbol + syms[i-1].symbol;
                                    n= n - syms[i-1].value + syms[shift].value;

                                    i=-1;


                              }
                              else
                              {
                                    s+=syms[i].symbol;
                                    n-=syms[i].value;
                                    i=-1;
                              }
                        }
                  }
            }
            return s;
      }
      public static void main(String s[])
      {
            Roman r=new Roman();
            System.out.print(toRoman(Integer.parseInt(s[0])));
      }

}


test this code

java Roman 101


Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

crystalfish0318Author Commented:
useless to me!
too complicated................><

by the way, i cannot use applet.

this is "User-Defined Class and ADT"
sudhakar_koundinyaCommented:
This can be simplified as application also


import java.text.*;



public class Roman extends NumberFormat
{      
      public StringBuffer format(double n, StringBuffer a, FieldPosition p)
      {
            return null;
      }
      public static class SymTab
      {
            
            char symbol;            
            long value;
      public SymTab(char s, long v) { this.symbol=s; this.value=v; }
   };
            public static Roman.SymTab syms[]= {
               new Roman.SymTab('M',1000),
                  new Roman.SymTab('D',500),
               new Roman.SymTab('C',100),
               new Roman.SymTab('L',50),
               new Roman.SymTab('X',10),
               new Roman.SymTab('V',5),
               new Roman.SymTab('I',1)
            };
      public Number parse(String text, ParsePosition parsePosition)
      {

      String s = text.substring(parsePosition.getIndex());
                  
       long tot=0,max=0;
       char ch[]=s.toUpperCase().toCharArray();
      int i,p;
      for(p=ch.length-1;p>=0;p--)
      {
            for(i=0;i<syms.length;i++)
            {
                  if(syms[i].symbol==ch[p])
                  {
                        if(syms[i].value>=max)
                              tot+= (max = syms[i].value);
                        else
                              tot-= syms[i].value;
                  }
            }
      }
      parsePosition.setIndex(s.length());
      return new Long(tot);
      }
      public static long toLong(String s)
      {
            long tot=0,max=0;
            char ch[]=s.toUpperCase().toCharArray();
            int i,p;
            for(p=ch.length-1;p>=0;p--)
             {
                  for(i=0;i<syms.length;i++)
                  {
                        if(syms[i].symbol==ch[p])
                        {
                              if(syms[i].value>=max)
                                    tot+= (max = syms[i].value);
                              else
                                    tot-= syms[i].value;
                        }
                  }
            }
            return tot;
      };
            public StringBuffer format(long n, StringBuffer s, FieldPosition p)
         {
                  int i;
                  while(n>0)
                  {
                        for(i=0;i<syms.length;i++)
                        {
                              if(syms[i].value<=n)
                              {
                                    int shift=i+(i%2);
                                    if( i>0 && shift<syms.length &&
                (syms[i-1].value-syms[shift].value) <= n )
                                    {
                                    s.append( syms[shift].symbol);
                                    s.append( syms[i-1].symbol);
                                    n= n - syms[i-1].value + syms[shift].value;

                                    i=-1;
                              }
                              else
                              {
                                    s.append(syms[i].symbol);
                                    n-=syms[i].value;
                                    i=-1;
                              }
                        }
                  }
            }
            return s;
      }

   public static String toRoman(long n)
   {
         int i;
            String s;
      s="";
      while(n>0)
      {
                  for(i=0;i<syms.length;i++)
            {
                        if(syms[i].value<=n)
                        {
                              int shift=i+(i%2);
                              if( i>0 && shift<syms.length &&
                                   (syms[i-1].value-syms[shift].value) <= n )
                              {
                                    s= s+ syms[shift].symbol + syms[i-1].symbol;
                                    n= n - syms[i-1].value + syms[shift].value;

                                    i=-1;


                              }
                              else
                              {
                                    s+=syms[i].symbol;
                                    n-=syms[i].value;
                                    i=-1;
                              }
                        }
                  }
            }
            return s;
      }
      public static void main(String s[])
      {
            Roman r=new Roman();
            try
            {
                  System.out.print(toRoman(Integer.parseInt(s[0])));
            }
            catch(Exception ex)
            {
                  System.out.print(toLong(s[0]));
            }
      }

}


method   toLong is used to convert roman numerals to integers
method   toRoman is used to convert numerals to roman numerals


try this code again

java Roman 101

   or

java Roman CM

sudhakar_koundinyaCommented:
method   toLong is used to convert roman numerals to integers
method   toRoman is used to convert numerals to roman numerals


try this code again

java Roman 101

  or

java Roman CM
crystalfish0318Author Commented:
How about this one?

public class ch8_num1
{
      public static void main(String args[])
      {
            if(args.length<1)
            System.out.println("Usage:java Roman number");
            
            else
            {
                  int i=0;
                  
                  try
                  {
                        i=Integer.parseInt(args[0]);
                        
                        if(i<1 || i>3999)
                        System.out.println("Enter a integer value between 1 and 3999 only...");
                        
                        else System.out.println("Roman equivalent of "+i+" is: "+toRoman(i));
                  }
                  
                  catch(Exception e)
                  
                  {
                        System.out.println("You have entered a wrong or invalid number.");
                         System.out.println(e.toString());
                         System.exit(0);
                   }//try-catch
             }//if-else
      }//main
      
      public static String toRoman(int number)
      {
            String roman="";int i;
            
            while(number>0)
            {
                  if(number>=1000)
                  {
                        i = number/1000;
                    number = number%1000;
                    
                    for(int j=0;j<i;j++) roman += "M";
              }
              
              else
              if(number>=900)
              {
                    number = number%900;
                    roman += "CM";
              }
              
              else
              if(number>=500)
              {
                    number = number%500;
                    roman += "D";
                     }
                     
                     else
                     if(number>=400)
                     {
                           number = number%400;    
                    roman += "CD";
                }
                
                else
                if(number>=100)
                {
                      i = number/100;
                    number = number%100;
                    for(int j=0;j<i;j++) roman += "C";
                }
                
                else
                if(number>=90)
                {
                      number = number%90;
                    roman += "XC";
                }
                
                else
                if(number>=50)
                {
                      number = number%50;
                    roman += "L";
              }
              
              else
              if(number>=40)
              {
                    number = number%40;
                    roman +="XL";
                }
                
                else
                if(number>=10)
                {
                      i = number/10;
                    number = number%10;
                    for(int j=0;j<i;j++) roman += "X";
                }
                
                else
                if(number>=9)
                {
                      number = number%9;
                         roman += "IX";
                }
                
                else
                if(number>=5)
                {
                      number = number%5;
                    roman += "V";
                }
                
                else
                if(number==4)
                {
                      number = number%4;
                      roman += "IV";
                }
                
                else
                if(number==3)
                {
                      roman += "III";
                     number=0;
                }
                
                else
                if(number==2)
                {
                      roman += "II";
                     number=0;
                }
                
                else
                if(number==1)
                {
                      roman += "I";
                     number=0;
                }//if-else
          }//while
               
               return roman;
      }//toRoman  
}//class


help me to run it.
I don't know why i can't do the testing.

4 reqiuirements
1) Store the number as a ROman numeral.
2) Convert and store the number into decimal
3) Print the number as a ROman numberal or decimal number as requested by the user.
The decimal values of the Roman numerals are:
M        1000
D          500
C          100
L            50
X           10
V             5
I              1

4) Test the program using the following Roman numerals:
    MCXIV, CCCLIX, and MDCLXVI.
crystalfish0318Author Commented:
sorry, i don't have much time.
only 20 min left..................><
sudhakar_koundinyaCommented:
What is the problem in your code?
Exactly what you are expecting from this code?

When I tested this code, this works only for number to roman numerals only. For roman to numeral you need to write another method

and as suggested in point 4, when i tested the following values( MCXIV, CCCLIX, and MDCLXVI. ). i got the fine results

regards,
sudha
crystalfish0318Author Commented:
how did you test it?
when i run it, it only shows:

Usage:java ROman number
Press any key to continue...


that's all
sudhakar_koundinyaCommented:
public class Roman1
{
     public static void main(String args[])
     {
          if(args.length<1)
          System.out.println("Usage:java Roman number");
         
          else
          {
               int i=0;
               
               try
               {
                    i=Integer.parseInt(args[0]);
                   
                    if(i<1 || i>3999)
                    System.out.println("Enter a integer value between 1 and 3999 only...");
                   
                    else System.out.println("Roman equivalent of "+i+" is: "+toRoman(i));
               }
               
               catch(Exception e)
               
               {
                    System.out.println("You have entered a wrong or invalid number.");
                      System.out.println(e.toString());
                      System.exit(0);
                 }//try-catch
            }//if-else
     }//main
     
     public static String toRoman(int number)
     {
          String roman="";int i;
         
          while(number>0)
          {
               if(number>=1000)
               {
                    i = number/1000;
                  number = number%1000;
                 
                  for(int j=0;j<i;j++) roman += "M";
             }
             
             else
             if(number>=900)
             {
                  number = number%900;
                  roman += "CM";
             }
             
             else
             if(number>=500)
             {
                  number = number%500;
                  roman += "D";
                  }
                 
                  else
                  if(number>=400)
                  {
                       number = number%400;    
                  roman += "CD";
              }
             
              else
              if(number>=100)
              {
                   i = number/100;
                  number = number%100;
                  for(int j=0;j<i;j++) roman += "C";
              }
             
              else
              if(number>=90)
              {
                   number = number%90;
                  roman += "XC";
              }
             
              else
              if(number>=50)
              {
                   number = number%50;
                  roman += "L";
             }
             
             else
             if(number>=40)
             {
                  number = number%40;
                  roman +="XL";
              }
             
              else
              if(number>=10)
              {
                   i = number/10;
                  number = number%10;
                  for(int j=0;j<i;j++) roman += "X";
              }
             
              else
              if(number>=9)
              {
                   number = number%9;
                      roman += "IX";
              }
             
              else
              if(number>=5)
              {
                   number = number%5;
                  roman += "V";
              }
             
              else
              if(number==4)
              {
                   number = number%4;
                   roman += "IV";
              }
             
              else
              if(number==3)
              {
                   roman += "III";
                   number=0;
              }
             
              else
              if(number==2)
              {
                   roman += "II";
                   number=0;
              }
             
              else
              if(number==1)
              {
                   roman += "I";
                   number=0;
              }//if-else
         }//while
             
             return roman;
     }//toRoman  
}//class



sudhakar_koundinyaCommented:

this is your code only.
Class : Roman1

my testing results for different numbers



C:\>java Roman1 1113
Roman equivalent of 1113 is: MCXIII

C:\>java Roman1 11
Roman equivalent of 11 is: XI

C:\>java Roman1 1100
Roman equivalent of 1100 is: MC

C:\>java Roman1 1130
Roman equivalent of 1130 is: MCXXX

C:\>java Roman1 2130
Roman equivalent of 2130 is: MMCXXX

C:\>java Roman1 210
Roman equivalent of 210 is: CCX

sudhakar_koundinyaCommented:
And I suggest my first program, as it works for both conversions

regards
sudha
crystalfish0318Author Commented:
so...........i have to save the file into drive c first?

then run?
sudhakar_koundinyaCommented:
You are using ch8_num1 as your class

so do like this
java ch8_num1 100
sudhakar_koundinyaCommented:
Ha ha

I think you are pure begnner Ok no problems

do like this.

1. Place Your code  in a text file and name it as Roman.java.
This may be c drive or any thing else
2. Make sure your class name and class file name should be same,. That means as we save it as Roman.java we need to name class as Roman ( You are using ch8_num1 as your class-  change it to Roman ) and save it as Roman.java. Hope you got my points till here
3. compile the class file javac Roman.java
4. execute the class file  java Roman 1000

crystalfish0318Author Commented:
i know how to compile. i'm just not good in programming.
besides, i'm using JCreator.
anyway, thank you very much

sudhakar_koundinya
crystalfish0318Author Commented:
nono, i didn't use the code that sudhakar_koundinya
had give me. Please look carefully. I only posted my whole codes, and asked the experts to check my codes for me.
sudhakar_koundinyaCommented:
Hi AnnieMod,

 I haven't done any home work for him. I just copied the code from this site  http://www.hawaga.org.uk/java/benno/number/Roman.java and pasted. Please look at end lines of my first comment. If this is against EE policy I will not this in future. And also he not accepted this code as it is complicated for him.

The second thing is he asked 4 points basically by posting his own code. But his code works for point one only. And also he did some mistakes while execution of the code. Just I suggest him howto exewcute that. Please read other comments of mine.

Anyway If the things what I did are against EE policy, I am sorry for that

thanks,
sudhakar

LunchyCommented:
crystalfish, as this was homework, you stated the problem in a way that indicates you hoped someone would provide the code.  It was only later you posted your own code.  Post your own code at the beginning if you want help with homework.  Experts may be able to help you with specific problems you are encountering, but not write the whole project.  

sudhakar, you will have to learn to be more vigilant as to which questioner's are looking for homework help.  If in doubt, ask the questioner if it is homework, and make your decision based on what the answer is.  If you think it is suspicious, we ask that you report it to Community Support, otherwise, as has happened here, you lose the time and effort you put into the question when it *is* reported to CS.

Lunchy
Friendly Neighbourhood Community Support Admin

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.