我想将整数转换为罗马数字,但收到错误incompatible types: int cannot be converted to boolean [in MainClass.java]
.它指的是声明,但我看不出有什么问题。
public String intToRoman(int num) {
if (num < 0 || num > 3999)
return Integer.toString(-1);
int nums[] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
String[] syms = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
StringBuilder sb = new StringBuilder();
int n=0;
for(int i = 12; 0 ; i--) {
int res=0;
if(num > nums[i]) {
res = num / nums[i];
for(int j=1 ; res ; j++) {
sb.append(syms[i]);
}
}
}
return sb.toString();
}
你的算法非常接近,首先没有罗马数字表示零;所以测试num
(或value
(至少是一个。其次,我将num
重命名为value
nums
因为很难区分。接下来,循环需要boolean
终止条件。在这里,您希望在i
小于零时终止外循环,在j
大于(或等于(value / nums[i]
时终止内循环。最后,由于您不使用实例状态,因此我将该方法设为static
.喜欢
public static String intToRoman(int value) {
if (value < 1 || value > 3999) {
return "-1";
}
int nums[] = { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 };
String[] syms = { "I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD",
"D", "CM", "M" };
StringBuilder sb = new StringBuilder();
for (int i = nums.length - 1; i >= 0; i--) {
if (value >= nums[i]) {
for (int j = 0; j < (value / nums[i]); j++) {
sb.append(syms[i]);
}
value %= nums[i];
}
}
return sb.toString();
}
我测试过,比如
public static void main(String[] args) {
for (int i = 1; i < 100; i++) {
System.out.println(intToRoman(i));
}
}
它似乎在这里正常工作。
在for loop
中,第一段是初始化,第二段是条件,第三段是变量中的递增或递减。
在您的第二个 for 循环中,您没有提到应该导致值boolean
true
/false
的条件。但是你提到了res
,它是int
型的.
请纠正代码,它将起作用。 转到此处以获取更多清晰度。
1.The first statement declares an int variable named i and assigns it the value 20. This statement is only executed once, when the for loop starts.
2.The second statement compares the value and The second statement in a for loop is a condition statement and needs to be a boolean. This statement is executed before each repetition of the for loop.
3.The third statement increments the value of i/j. This statement is also executed once per iteration of the for loop, after the body of the for loop is executed.
These statements each have a different role in the execution of the for loop.
These roles are:
1.Loop initializer
2.Loop condition
3.Post iteration operation