2

For an assignment we're given these two arrays:

private final static int[] NUMBERS= {1000,900,500,400,100,90,50,40,10,9,5,4,1};

private final static String[] LETTERS = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};

The objective is to create a method that will give the user a conversion for the numeric expression they give and turn it into roman numerals.

I am just wondering how you can make the two array's index points match up so that they have the same indexOf so I can create the method that returns the corresponding numeral.

I know that:
the arrays match up with each other in their values

But I don't know:
how to express combining the two arrays to get one return which is the roman numeral. I would also be grateful if I could see other examples for learning string arrays.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Possible duplicate of [Converting Integers to Roman Numerals - Java](http://stackoverflow.com/questions/12967896/converting-integers-to-roman-numerals-java) – gotnull Jan 25 '17 at 05:26

3 Answers3

1

Sounds like a job for a HashMap rather than two separate arrays. This allows you to create a series of <key,value> pairs. Like so

public static HashMap<String, Integer> myMapping = new HashMap<String, Integer>();
myMapping.put("M", 1000);
myMapping.put("CM", 900);
...
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
James
  • 903
  • 7
  • 22
1

First approach: Store numbers and their corresponding roman equivalent in a Map, and then you can then simply fetch the roman value associated with each number. You can find approach here: Converting Integers to Roman Numerals - Java


Second ways is to define a function like I have given below:

private final static int[] NUMBERS= {1000,900,500,400,100,90,50,40,10,9,5,4,1}; 
private final static String[] LETTERS = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};

public static String returnRoman(int number)
{
    int index=0;
    for(int i=0;i<NUMBERS.length;i++)
    {
        if(NUMBERS[i]==number)
        {
            index=i;
            break;
        }
    }
    if(index==0)
    return "Not found";
    else
    return LETTERS[index];
}
Community
  • 1
  • 1
abhinav3414
  • 946
  • 3
  • 9
  • 31
0

Why not try

return NUMBERS.indexOf(number) == -1 ? "" : LETTERS[NUMBERS.indexOf(number)];

VHS
  • 9,534
  • 3
  • 19
  • 43