Write a Java program to convert Roman number to an integer number


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

Kindle Paperwhite High Resolution Display Tablet | Rs. 9999

  1. public class Javamathexcercise {
  2. public static void main(String[] args) {
  3.  
  4. String str = "XXVIVI";
  5. int len = str.length();
  6.  
  7. str = str + " ";
  8. int result = 0;
  9. for (int i = 0; i < len; i++) {
  10. char ch = str.charAt(i);
  11. char next_char = str.charAt(i+1);
  12.  
  13. if (ch == 'M') {
  14. result += 1000;
  15. } else if (ch == 'C') {
  16. if (next_char == 'M') {
  17. result += 900;
  18. i++;
  19. } else if (next_char == 'D') {
  20. result += 400;
  21. i++;
  22. } else {
  23. result += 100;
  24. }
  25. } else if (ch == 'D') {
  26. result += 500;
  27. } else if (ch == 'X') {
  28. if (next_char == 'C') {
  29. result += 90;
  30. i++;
  31. } else if (next_char == 'L') {
  32. result += 40;
  33. i++;
  34. } else {
  35. result += 10;
  36. }
  37. } else if (ch == 'L') {
  38. result += 50;
  39. } else if (ch == 'I') {
  40. if (next_char == 'X') {
  41. result += 9;
  42. i++;
  43. } else if (next_char == 'V') {
  44. result += 4;
  45. i++;
  46. } else {
  47. result++;
  48. }
  49. } else { // if (ch == 'V')
  50. result += 5;
  51. }
  52. }
  53. System.out.println("\nRoman Number: "+str);
  54. System.out.println("Equivalent Integer: "+result+"\n");
  55. }
  56. }

Result

java techstudy.org

     





Related Topics


Responses




Popular Posts

Facebook

Founded in 2016, Tech Study passionately delivers stylish and dynamic innovative information to programmer and technology lovers. http://www.techstudy.org/.