Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Roman {
- static char[] characters = new char[] {'C', 'L', 'X', 'V', 'I'};
- static int[] values = new int[] {100, 50, 10, 5 , 1};
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("Veuillez entrer un chiffre romain: ");
- String number = sc.nextLine();
- int converted = 0;
- for(int i = 0; i < number.length(); i++) {
- char c = number.charAt(i);
- if((number.length() > 1 && i < number.length() - 1) && (charOffset(c, number.charAt(i+1))) > 0) { // Si le nombre contient plus de 1 caractère et que le caractère étudié est avant l'avant dernier comme avec IX ou XL
- converted += getCharValue(number.charAt(i+1)) - getCharValue(c); // Ajout de la valeur du caractère supérieur moins la valeur du caractère ex: avec XL: +50-10 = 40
- i++; // On saute un nombre comme IX équivaut à un ajout
- } else { // S'il n'y a pas de cas comme IX / XL on ajoute normalement la valeur du nombre
- converted += getCharValue(c);
- }
- }
- System.out.println("Nombre converti: "+converted);
- }
- static int getCharIndex(char c) { // Renvoie l'index d'un caractère ex: L => 1
- for(int i = 0; i < characters.length; i++)
- if(characters[i] == c) return i;
- return 0;
- }
- static int getCharValue(char c) { // Renvoie la valeur du caractère ex: 'X' => 10
- return values[getCharIndex(c)];
- }
- static int charOffset(char a, char b) { // Renvoie l'écart entre deux caractères ex: a = 'I' b = 'X' renvoie 4 - 2 = 2
- return getCharIndex(a) - getCharIndex(b);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement