Solved

Convert Roman Numbers to Decimal Numbers

Posted on 2001-07-24
7
686 Views
Last Modified: 2009-12-16
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.

it should not accept invalid
inputs like space, empty strings, digits and other characters other than the mentioned above and and also the maximum number of char. inputted shld. be 18

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
Comment
Question by:macjacinto
  • 4
  • 2
7 Comments
 
LVL 1

Accepted Solution

by:
poluru earned 300 total points
ID: 6311757
to check no. of characters in a String str
str.length()
i have added some more functionality
to exit the appl type exit
and it wont allow the chars other than I,V,C,L,D,M

import java.io.InputStreamReader;
import java.util.Vector;

public class todecimal
{
    static String errMsg;
    static Vector romanChars;

    static
    {
            romanChars=new Vector();
            romanChars.add(new Character('I'));
            romanChars.add(new Character('V'));
            romanChars.add(new Character('X'));
            romanChars.add(new Character('L'));
            romanChars.add(new Character('C'));
            romanChars.add(new Character('D'));
            romanChars.add(new Character('M'));
      }

    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));
                   String line=br.readLine().toUpperCase();
                   if(line.equalsIgnoreCase("exit"))
                   {
                                 System.out.print("Do you really want to exit ? (yes/no) default(no)  :");
                                 String flag=br.readLine();
                                 if(flag.equalsIgnoreCase("yes"))
                                 System.exit(0);
                                 else
                                 continue;
                           }
                   else
                   {
                         boolean b=validate(line);
                         if(b)       System.out.println(getDecimal(line.toUpperCase()));
                         else      System.out.println(errMsg);
                   }

              }
    }

    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]);
                   break;
              }
              else if(i==0 && !first)
              {
                   sum-=getMultiplier(ch[i]);
                   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;
    }

      static boolean validate(String str)
      {
            char ch[]=str.toCharArray();
            for(int i=0;i<ch.length;i++)
            {
                  if(str.length()>18)
                  {
                        errMsg="Please enter a Roman number of max 18 characters!!!";
                        return false;
                  }
                  else if(!romanChars.contains(new Character(ch[i])))
                  {
                        errMsg="Invalid Character \""+ch[i]+"\" entered";
                        return false;
                  }
                  
            }
            return true;
      }
}
0
 
LVL 7

Expert Comment

by:tomboshell
ID: 6311782
hmm, homework?  Download the JavaDocs from Sun.  It will become a great help and the .length() function can easily be found in there under java.lang.String.

Depending how far you are in your studies using just the dos screen or into gui yet?  one way you present your question and await keyboard input, the other way you create a dialog box and wait for a selection.  Sounds like the dos screen though.  Just remember the 'if' statement and the others that go with it.

The running twice sounds like a debugging error and which you will have to trace your code.  

Don't want to just give you the answers, but I can help you think about the solution.  Don't mind mentioning the '.length()' function since I sometimes forget exactly what some function was called for a couple of seconds.  Take some time and go throught the Java Tutorial at http://java.sun.com/docs/books/tutorial/
It will help you, and get the JavaDocs (It is always my first check)

Tom
0
 
LVL 1

Expert Comment

by:poluru
ID: 6311953
did u check the above program ???
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:macjacinto
ID: 6320542
no but im giving you the poits anyway bec i wasnt able to make it on time. tnx for the time.
0
 

Author Comment

by:macjacinto
ID: 6320547
no but im giving you the poits anyway bec i wasnt able to make it on time. tnx for the time.
0
 
LVL 1

Expert Comment

by:poluru
ID: 6320686
hi,
but i dint get any points !!!!
Do U Accepted My Question ??? and graded it ???
0
 
LVL 1

Expert Comment

by:poluru
ID: 6321240
Thanx for the points....
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Core Java. What output will be and why ? 6 66
Securing Jmx Console and web console 2 65
xampp tool 12 26
configure dependency in POM for new database 3 17
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

920 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now