Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public int convertToInt(String roman) {
- //A while loop that loops for the value of length of the roman string entered subtracted by 1 to properly loop through each numeral
- //A while loop is used instead of a for loop for more control within the loop allowing for a proper loop through each numeral
- while(numeralIndex < roman.length()-1) {
- numeralIndex++;
- //This variable stores the current numeral that the loop is iterating through in the entire roman numeral
- numeral = String.valueOf(roman.charAt(numeralIndex));
- //If the loop is at the last roman numeral it will obtain the numeral before it and put it first and combine it with the current numeral after it
- if(numeralIndex == roman.length()-1)
- numeral2 = ((String.valueOf(roman.charAt(numeralIndex-1)) + numeral));
- else //If not, it will set numeral2 to combine the numeral first with the numeral after it
- numeral2 = (numeral + (String.valueOf(roman.charAt(numeralIndex+1))));
- //This will be used later to check if it equals one of the numerals following the subtraction method i.e CM
- //If the current numeral in the loop corresponds to one of the numerals it will add its corresponding decimal value to a total sum variable "decimal"
- if(numeral.equals("M")) {
- decimal += 1000;
- }
- else if(numeral2.equals("CM")) {
- //The same step is done with the numerals following the subtraction method as the singular numerals
- //Although, the numeral index is moved 2x through the loop due to 2 numerals being involved
- decimal += 900;
- numeralIndex++;
- }
- else if(numeral.equals("D")) {
- decimal += 500;
- }
- else if(numeral2.equals("CD")) {
- decimal += 400;
- numeralIndex++;
- }
- else if(numeral.equals("C")) {
- decimal += 100;
- }
- else if(numeral2.equals("XC")) {
- decimal += 90;
- numeralIndex++;
- }
- else if(numeral.equals("L")) {
- decimal += 50;
- }
- else if(numeral2.equals("XL")) {
- decimal += 40;
- numeralIndex++;
- }
- else if(numeral.equals("X")) {
- decimal += 10;
- }
- else if(numeral2.equals("IX")) {
- decimal += 9;
- numeralIndex++;
- }
- else if(numeral.equals("V")) {
- decimal += 5;
- }
- else if(numeral2.equals("IV")) {
- decimal += 4;
- numeralIndex++;
- }
- else if(numeral.equals("I")) {
- decimal += 1;
- }
- }
- //Once there are no more numerals to loop through it will return the converted decimal value of the roman numeral
- return decimal;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement