尝试设计一个读取整数的应用程序,并打印2和输入值之间的所有偶数之和。最后一点可以帮助我吗?!
import java.util.Scanner;
public class IntegerValue {
// main method
public static void main(String[] args) {
// Data fields
int a;
// end
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer greater than 1");
a = sc.nextInt();
if (a <= 1) {
System.out.println("Input Value must not be less than 2");
}
while (a > 1) {
int sum = 0;
if (a % 2 == 0) {
sum += a;
a = a - 1;
}
System.out.println(sum);
}
}
}
答案 0 :(得分:2)
最重要的部分,已经指出了初始化的总和;但似乎他们错过了印刷部分;在循环执行后打印sum会更好。所以这就是你的程序的最后一部分最好是这样的:
int sum = 0;
while (a > 1) {
if (a % 2 == 0) {
sum += a;
a = a - 1;
}
}
System.out.println(sum);
答案 1 :(得分:1)
您需要在sum
循环中定义while
变量,否则每次迭代循环都会重新初始化。如果您只想要最终总和,也应该在while循环外打印sum。这是代码更新,您可以尝试:
int sum = 0;
while (a > 1) {
if (a % 2 == 0) {
sum += a;
a = a - 1;
}
}
System.out.println(sum);