Reputation: 21
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.
Upvotes: 2
Views: 3320
Reputation: 967
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];
}
Upvotes: 1
Reputation: 10194
Why not try
return NUMBERS.indexOf(number) == -1 ? "" : LETTERS[NUMBERS.indexOf(number)];
Upvotes: 0
Reputation: 923
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);
...
Upvotes: 1