Solved

Convert Roman Numbers to Decimal Numbers

Posted on 2001-07-24
7
684 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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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…
This video teaches viewers about errors in exception handling.

708 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

17 Experts available now in Live!

Get 1:1 Help Now