2 回答

TA貢獻2039條經驗 獲得超8個贊
問題出在條件上。由于要么i % 3ori % 5首先滿足,所以它永遠不會達到i % 3 == 0 && i % 5 == 0條件。因此,您必須首先檢查i % 3 == 0 && i % 5 == 0然后檢查其余兩個條件。
以下是修改后的條件:
if (i % 3 == 0 && i % 5 == 0){
System.out.println("FlimFlam");
} else if (i % 3 == 0) {
System.out.println("Flim");
} else if (i % 5 == 0) {
System.out.println("Flam");
} else {
System.out.println(i);
}
編輯: - if-else-if 塊就像如果任何第一個出現的條件匹配,則不要檢查 if-else-if 塊中的其余條件。

TA貢獻1866條經驗 獲得超5個贊
這是完整的代碼:
public class Example {
public static void main(String argv[]) {
if (argv.length != 1)
usage();
int n = 0;
try {
n = Integer.parseInt(argv[0]);
} catch (NumberFormatException e) {
usage();
}
for (int i = 1; i <= n; i++)
if (i % 3 == 0) {
if(i % 5 == 0) {
System.out.println("FlimFlam");
}
System.out.println("Flim");
} else if (i % 5 == 0) {
System.out.println("Flam");
} else {
System.out.println(i);
}
}
private static void usage() {
System.err.println("usage: java Example count string");
System.exit(1);
}
}
添加回答
舉報