60 lines
2.4 KiB
Java
60 lines
2.4 KiB
Java
// Question 1
|
|
// Import the LinkedHashMap and Scanner
|
|
import java.util.*;
|
|
|
|
|
|
public class Main {
|
|
|
|
/* I chose to approach this with an algorithm that has a map with the values in the range
|
|
Then it takes the input, and divides it by the largest number. We will append the roman numeral of that larger
|
|
number the amount of times that it divides. Then go to the next next largest number, and repeat.
|
|
Example: 80. 90 does not divide into 80 once, so nothing is appended to the string. 50 does divide into 80 once,
|
|
so we append 'L'(50) to the return string. Using module, we take the remaining 30. 10 divides into 30 evenly 3 times
|
|
So 3 'X'(10) are appended. We divide 40 and 9 to account for 'IX' and 'IV'
|
|
*/
|
|
static String create_roman(int input) {
|
|
int divide_count = 0; // Counts the amount of times the number divides into input
|
|
String roman = ""; // Return string we append to
|
|
|
|
// Ordered map that holds the numbers and their roman equivalents
|
|
Map<Integer, String> test = new LinkedHashMap<>();
|
|
test.put(90, "XC");
|
|
test.put(50, "L");
|
|
test.put(40, "XL");
|
|
test.put(10, "X");
|
|
test.put(9, "IX");
|
|
test.put(5, "V");
|
|
test.put(4, "IV");
|
|
test.put(1, "I");
|
|
|
|
// Loop through all the numbers in the map
|
|
for(var x : test.entrySet()) {
|
|
// Divide input by the number we are on(starts at 90)
|
|
divide_count = input / x.getKey();
|
|
// Change input value to the remainder
|
|
input %= x.getKey();
|
|
// This loop appends to return string the amount of times the number was divided in
|
|
while(divide_count-- > 0) {
|
|
roman = roman.concat(x.getValue());
|
|
}
|
|
}
|
|
return roman;
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
// Store user input
|
|
int input;
|
|
// Scanner object for user input
|
|
Scanner scanner = new Scanner(System.in);
|
|
|
|
// Ask for user input util user enters something between 1 and 90, inclusively
|
|
do {
|
|
System.out.print("Enter an integer between 1 and 90, inclusively: ");
|
|
input = scanner.nextInt();
|
|
} while (input < 1 || input > 90); // Ask for input again if not in range of [1,90]
|
|
|
|
|
|
// Print out final result
|
|
System.out.println("Roman numeral of " + input + ": " + create_roman(input));
|
|
}
|
|
} |