#9025: java 一直RE~請高手幫忙


z5902047 (andy)

學校 : 不指定學校
編號 : 41412
來源 : [61.58.171.189]
最後登入時間 :
2014-07-24 23:01:51
a013. 羅馬數字 -- NPSC 模擬試題 | From: [61.58.171.189] | 發表日期 : 2014-07-22 20:31

 Eclipse 以及測試執行都正常
 
import java.util.Scanner;

public class JAVA {
public static void main(String[] arge) {
Scanner sca = new Scanner(System.in);
String a, b;
int sum = 0, sum2 = 0;
while (sca.hasNext()) {

a = sca.next();
//判斷是否為結束符號
if (a.equals("#")) {
break;
} else {
b = sca.next();
//文字數字取代
a = a.replaceAll("IV", "4 ");
a = a.replaceAll("IX", "9 ");
a = a.replaceAll("XL", "40 ");
a = a.replaceAll("XC", "90 ");
a = a.replaceAll("CD", "400 ");
a = a.replaceAll("CM", "900 ");
a = a.replaceAll("I", "1 ");
a = a.replaceAll("V", "5 ");
a = a.replaceAll("X", "10 ");
a = a.replaceAll("L", "50 ");
a = a.replaceAll("C", "100 ");
a = a.replaceAll("V", "500 ");
a = a.replaceAll("M", "1000 ");
String[] aArray = a.split(" ");
//將a取代之數字相加
for (String d : aArray) {
sum += Integer.parseInt(d);
}
b = b.replaceAll("IV", "4 ");
b = b.replaceAll("IX", "9 ");
b = b.replaceAll("XL", "40 ");
b = b.replaceAll("XC", "90 ");
b = b.replaceAll("CD", "400 ");
b = b.replaceAll("CM", "900 ");
b = b.replaceAll("I", "1 ");
b = b.replaceAll("V", "5 ");
b = b.replaceAll("X", "10 ");
b = b.replaceAll("L", "50 ");
b = b.replaceAll("C", "100 ");
b = b.replaceAll("D", "500 ");
b = b.replaceAll("M", "1000 ");
String[] bArray = b.split(" ");
//將b取代之數字相加
for (String d : bArray) {
sum2 += Integer.parseInt(d);
}
//判斷大小,使結果皆為正
if (sum >= sum2)
sum -= sum2;
else
sum = sum2 - sum;
if (sum == 0) {
System.out.println("ZERO");
} else {
String pr = "";
//將文字轉換為字串
while (sum >= 1000) {
sum -= 1000;
pr += "M";
}
while (sum >= 900) {
sum -= 900;
pr += "CM";
}
while (sum >= 500) {
sum -= 500;
pr += "D";
}
while (sum >= 400) {
sum -= 400;
pr += "CD";
}
while (sum >= 100) {
sum -= 100;
pr += "C";
}
while (sum >= 90) {
sum -= 90;
pr += "XC";
}
while (sum >= 50) {
sum -= 50;
pr += "L";
}
while (sum >= 40) {
sum -= 40;
pr += "XL";
}
while (sum >= 10) {
sum -= 10;
pr += "X";
}
while (sum >= 9) {
sum -= 9;
pr += "IX";
}
while (sum >= 5) {
sum -= 5;
pr += "V";
}
while (sum >= 4) {
sum -= 4;
pr += "IV";
}
while (sum >= 0) {
sum -= 1;
pr += "I";
}
System.out.println(pr);
}

}
}

}
}
 
#10535: Re:java 一直RE~請高手幫忙


sc2830704 (AS)

學校 : 不指定學校
編號 : 27271
來源 : [36.230.203.79]
最後登入時間 :
2015-12-09 20:12:06
a013. 羅馬數字 -- NPSC 模擬試題 | From: [36.230.203.79] | 發表日期 : 2015-12-09 17:28

三個問題

1.sum,sum2不該放在while外面,或者每次while開始前都要設為0

2.轉換int的部份 a.replaceAll("D","500 "),打成V

3.轉換string while(sum>0),用>=0會加1

 
ZeroJudge Forum