Solved

Convert Roman Numbers to Decimal Numbers

Posted on 2001-07-24
7
688 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

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

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

773 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