import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i;
int input;
/*创建两个罗马数字转换参照的集合*/
ArrayList<Integer> a = new ArrayList<Integer>();
Collections.addAll( a, 1000,900,500,400,100,90,50,40,10,9,5,4,1 );
ArrayList<String> b = new ArrayList<String>();
Collections.addAll( b, "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" );
System.out.print("请输入:");
Scanner scanner = new Scanner( System.in );
/*限制输入的数要大于零*/
while(true) {
input = scanner.nextInt();
if ( input > 0 ) {
break;
}else {
System.out.print("有误!重新输入:");
}
}
while(true) {
/*每次循环都将input的值放入a集合中并将它们降序排序*/
a.add( input );
Collections.sort(a,new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2 - o1;
}
});
/*排完序后获取input的值在集合a中的索引,并在集合b中同样的索引处添加一个元素null*/
i = a.indexOf( input );
b.add( i, "null" );
/*用input的值减去下一个元素的值并将差再次赋给input,若差不是负数则输出b集合中的第i+1号元素*/
input -= a.get( i + 1 );
if ( input >= 0 ) {
System.out.print( b.get( i + 1 ));
/*分别从集合中去除第i号元素*/
a.remove( i );
b.remove( i );
}
/*循环多次,直到input值为0就退出循环*/
if ( input == 0 ) {
break;
}
}
}
}
Java实现阿拉伯数字转换成罗马数字
最新推荐文章于 2024-06-27 15:25:28 发布