尝试设计一个读取整数并打印 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);
}
}
}
最佳答案
最重要的部分,正在初始化的 sum 已经指出了;但他们似乎错过了打印部分;最好在循环执行后打印 sum 。因此,程序的最后一部分最好如下所示:
int sum = 0;
while (a > 1) {
if (a % 2 == 0) {
sum += a;
a = a - 1;
}
}
System.out.println(sum);
关于java - 更好地使用 for 和 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18479118/