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.

1

3 Answers 3

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think the function helps me the most and I understand this solution the most. Thank you so much for your help.
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);
...

Comments

0

Why not try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.