Java编程练习-4 循环、if语句、四则运算
5和11
编写一个程序,计算可被5或11整除,且小于等于自然数n的所有正数之和。
该程序应首先打印出提示请输入数字,再读取输入数字。它应计算并输出所有小于等于n的可被5或11整除的正数之和。如果用户输入一个负数,则打印错误:n>= 0程序结束。
例如,如果用户输入数字57,则必须将数字5、10、11、15、20、22、25、30、33、35、40、44、45、50和55相加,结果为440。
编程练习答案
public class FiveAndEleven {
public static void main(String[] args) {
int n = giveInt("请输入数字:");
if (n < 0) {
System.out.println("错误:n>= 0");
} else {
int sum = 0;
while (n > 2) {
if (n % 5 == 0 || n % 11 == 0) {
sum += n;
}
n--;
}
System.out.println(sum);
}
}
public static int giveInt(String text) {
Integer x = null;
do {
String s = readString(text);
if (s == null)
throw new IllegalStateException(
"Illegal input!");
try {
x = Integer.parseInt(s.trim());
} catch (@SuppressWarnings("unused") NumberFormatException e) {
// try again
}
} while (x == null);
return x;
}
}
914

被折叠的 条评论
为什么被折叠?



