|
Trouver une ressource
Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !
ROMANOP : UN UTILITAIRE POUR LES NOMBRES ROMAINS (CONVERSION ROMAN -> ENTIERS, ENTIERS -> ROMAINS, CALCULS...)
Information sur la source
Description
Voici une utilitaire sur les nombres romains. Il permet la conversion de nombres romains vers les entiers et inversement. Il dispose aussi d'un méthode calc() qui prend deux chaines de caractères représentant deux nombres romains et un char correspondant à l'opérateur. Il retourne le résultat sous la forme d'une chaine de caractère représentant le résultat du calcul sous forme romaine. Cette classe est facilement utilisable pour tout code manipulant les nombres romains. Un class Main est incluse pour vous aider à comprendre son fonctionnement.
Source
- package romanop;
-
- import java.util.*;
-
- /**
- * @author Delache Michaël
- */
- public class RomanOp {
- private static final List<String> keys = new ArrayList<String>();
- private static final List<Integer> values = new ArrayList<Integer>();
-
- /**
- * Constructor of the RomanCalc class, initializes the two tables
- */
- public RomanOp() {
- keys.add("M");
- values.add(1000);
- keys.add("CM");
- values.add(900);
- keys.add("D");
- values.add(500);
- keys.add("CD");
- values.add(400);
- keys.add("C");
- values.add(100);
- keys.add("XC");
- values.add(90);
- keys.add("L");
- values.add(50);
- keys.add("XL");
- values.add(40);
- keys.add("X");
- values.add(10);
- keys.add("IX");
- values.add(9);
- keys.add("V");
- values.add(5);
- keys.add("IV");
- values.add(4);
- keys.add("I");
- values.add(1);
- }
- /**
- * Convert Roman to int
- * @param s Roman number
- * @return An int representing the roman number
- */
-
- public int toInt(final String s) {
- int res = 0;
- int size = s.length();
- String tmp = "";
- if (size == 1) {
- res = this.getInt(s);
- }
- if (size == 2) {
- if (keys.contains(s)) {
- res = this.getInt(s);
- }
- else {
- res += this.toInt(s.substring(0,1));
- res += this.toInt(s.substring(1,2));
- }
- }
- if (size > 2) {
- if (keys.contains(tmp = s.substring(size-2, size))) {
- res += this.getInt(tmp);
- res += this.toInt(s.substring(0, size-2));
- }
- else {
- tmp = s.substring(size-1, size);
- res += this.getInt(tmp);
- res += this.toInt(s.substring(0, size-1));
- }
- }
- return res;
- }
-
- /**
- * Returns the integer value of the roman value given by <i>s</i> or 0 if <i>s</i> is not in the table
- */
- public int getInt(final String s) {
- int res = 0;
- for (String str : keys) {
- if (str.equals(s)) {
- int index = keys.indexOf(str);
- res = values.get(index);
- }
- }
- return res;
- }
-
- /**
- * Converts integer value into roman value
- * @param i the integer to convert
- * @return a string representing the roman value
- */
- public String toRoman(final int i) {
- int cpt = i;
- String res = "";
- while (cpt > 0) {
- for (int j : values) {
- if ((cpt/j) >= 1) {
- int index = values.indexOf(j);
- res += keys.get(index);
- cpt -= j;
- break;
- }
- }
- }
- return res;
- }
-
- /**
- * Calculates the result of the operation determined by the two operands and the operator
- * @param x operand 1
- * @param y operand 2
- * @param op operator
- * @return the result
- */
- public String calc (final String x, final String y, final char op) {
- if (this.isOk(x) && this.isOk(y)) {
- int x1 = this.toInt(x);
- int y1 = this.toInt(y);
- switch (op) {
- case '+' :
- return this.toRoman(x1 + y1);
- case '-' :
- return this.toRoman(x1 - y1);
- case '*' :
- return this.toRoman(x1 * y1);
- case '/' :
- return this.toRoman(x1 / y1);
- default :
- break;
- }
- }
- return null;
- }
-
- /**
- * Says if the roman value given by <i>s</i> respect the roman value syntax
- * @param s the roman value to verify
- * @return true if <i>s</i> is correctly formed according to the roman value syntax (ie IV for 4 and not IIII), false else
- */
- public Boolean isOk(final String s) {
- int i = this.toInt(s);
- String str = this.toRoman(i);
- return s.equals(str);
- }
-
- }
package romanop;
import java.util.*;
/**
* @author Delache Michaël
*/
public class RomanOp {
private static final List<String> keys = new ArrayList<String>();
private static final List<Integer> values = new ArrayList<Integer>();
/**
* Constructor of the RomanCalc class, initializes the two tables
*/
public RomanOp() {
keys.add("M");
values.add(1000);
keys.add("CM");
values.add(900);
keys.add("D");
values.add(500);
keys.add("CD");
values.add(400);
keys.add("C");
values.add(100);
keys.add("XC");
values.add(90);
keys.add("L");
values.add(50);
keys.add("XL");
values.add(40);
keys.add("X");
values.add(10);
keys.add("IX");
values.add(9);
keys.add("V");
values.add(5);
keys.add("IV");
values.add(4);
keys.add("I");
values.add(1);
}
/**
* Convert Roman to int
* @param s Roman number
* @return An int representing the roman number
*/
public int toInt(final String s) {
int res = 0;
int size = s.length();
String tmp = "";
if (size == 1) {
res = this.getInt(s);
}
if (size == 2) {
if (keys.contains(s)) {
res = this.getInt(s);
}
else {
res += this.toInt(s.substring(0,1));
res += this.toInt(s.substring(1,2));
}
}
if (size > 2) {
if (keys.contains(tmp = s.substring(size-2, size))) {
res += this.getInt(tmp);
res += this.toInt(s.substring(0, size-2));
}
else {
tmp = s.substring(size-1, size);
res += this.getInt(tmp);
res += this.toInt(s.substring(0, size-1));
}
}
return res;
}
/**
* Returns the integer value of the roman value given by <i>s</i> or 0 if <i>s</i> is not in the table
*/
public int getInt(final String s) {
int res = 0;
for (String str : keys) {
if (str.equals(s)) {
int index = keys.indexOf(str);
res = values.get(index);
}
}
return res;
}
/**
* Converts integer value into roman value
* @param i the integer to convert
* @return a string representing the roman value
*/
public String toRoman(final int i) {
int cpt = i;
String res = "";
while (cpt > 0) {
for (int j : values) {
if ((cpt/j) >= 1) {
int index = values.indexOf(j);
res += keys.get(index);
cpt -= j;
break;
}
}
}
return res;
}
/**
* Calculates the result of the operation determined by the two operands and the operator
* @param x operand 1
* @param y operand 2
* @param op operator
* @return the result
*/
public String calc (final String x, final String y, final char op) {
if (this.isOk(x) && this.isOk(y)) {
int x1 = this.toInt(x);
int y1 = this.toInt(y);
switch (op) {
case '+' :
return this.toRoman(x1 + y1);
case '-' :
return this.toRoman(x1 - y1);
case '*' :
return this.toRoman(x1 * y1);
case '/' :
return this.toRoman(x1 / y1);
default :
break;
}
}
return null;
}
/**
* Says if the roman value given by <i>s</i> respect the roman value syntax
* @param s the roman value to verify
* @return true if <i>s</i> is correctly formed according to the roman value syntax (ie IV for 4 and not IIII), false else
*/
public Boolean isOk(final String s) {
int i = this.toInt(s);
String str = this.toRoman(i);
return s.equals(str);
}
}
Conclusion
Bien évidemment, vous êtes entièrement libre (et même encouragés) de modifier/copier/distribuer ce source. Si vous voyez des améliorations et/ou bugs dans ce code, je vous invite à me prévenir par email. Vous pourrez récupérer, ci-joint, un fichier zip contenant les dossier src (source) et doc (Documentation Java) ainsi qu'un fichier jar exécutable.
Fichier Zip
Pour les "Membres Club", vous pouvez télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !
Télécharger le zip
Historique
- 03 juin 2008 15:19:38 :
- Modification des modificateurs pour les attributs keys et values afin de les rendre static
- 03 juin 2008 16:39:01 :
- Modification du code de la méthode calc.
Tests "if" remplacés par un switch
- 04 juin 2008 11:38:32 :
- Modifications mineures dont quelques appels non statiques changés en appels statiques vers les attributs keys et values de la classe RomanOp
- 04 juin 2008 11:39:02 :
- Modifications mineures dont quelques appels non statiques changés en appels statiques vers les attributs keys et values de la classe RomanOp
Sources de la même categorie
Sources en rapport avec celle ci
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
Conversion String / Int [ par Skeetle ]
J'ai un petit soucis, je cherche desespérément à convertir une String en entier...Je m'expliqueDans le code " String toto = "2"; ", je veux pouvoir
conversion d'une chaine de caractére en entier [ par moooonaaaa ]
Salem,j'ai une chaine de caractére de la forme suivante"a.b.c.d"je veux faire un test sur ces valeurs.Il faut que tous soit des entiers.j'utilise Toke
2003-02-01 to 01/02/2003 conversion ou quoi ?? [ par amine1234Z ]
Salutlorsque je click sur un bouton, la zone de texte txt_Valeur reçoit comme valeur: 2003-02-01 moi je veux la rendre comme : 01/02/2003est ce que je
Remplacement d'un mot par le renvoi d'une fonction dans un string [ par tenev911 ]
Bonjour, J'ai un problème plutot génant, j'ai posté ce sujet sur developpez.com sans grand résultat, j'aurai surement plus de chance ici :) J'ai act
applets, écouteurs d'évènement [ par hiera ]
Bonjour, je suis un débutant en développement java et jaimerai savoir comment je pourrais écrire un programme permettant à l'utilisateur de saisir un
tester si la zone de texte contien des nombres et pas des caractaires [ par amine1234Z ]
Salut voila comme le titre de cette discution l'indique, j'ai une Zone de texte TXTO qui est distiner pour contenire un nombre réelString SSSS=TXTO
un petit pb de conversion [ par bidules ]
bonjour,voila g créé une grille de bouton en faisant un gridlayout. Pour créer les boutons je fais en toute logique un "for" mais voila j'aimerais num
Conversion d'un string en float ou double [ par massat ]
Bonjour,je suis débutant en java depuis 2 jours. J'essaye de créer une simple calculatrice afin de m'améliorer.J'arrive à transformer des string en in
Conversion d'un string en float ou double [ par massat ]
Bonjour,je suis débutant en java depuis 2 jours. J'essaye de créer une simple calculatrice afin de m'améliorer.J'arrive à transformer des string en in
pixelgrabber - conversion RGB/int [ par lutecefalco ]
qd on utilise un pixelgrabber et pixelgrab(), ça remplit un tableau d'entiers en fonction du code RGB.Je trouve pas l'algo qui permet de passer du cod
|
Téléchargements
Logiciels à télécharger sur le même thème :
|