How to find even numbers in Java?
To find the sum of even numbers, one can use a loop to iterate from 1 to a specified range, and then check if each number is even. If it is even, add it to the sum.
Here is an example code to find the sum of even numbers:
public class EvenSum {
public static void main(String[] args) {
int range = 10; // 指定的数字范围
int sum = 0; // 偶数和的初始值
for (int i = 1; i <= range; i++) {
if (i % 2 == 0) { // 判断是否为偶数
sum += i; // 将偶数累加到求和的结果中
}
}
System.out.println("偶数和为: " + sum);
}
}
In the above code, we use a for loop to iterate through each number from 1 to a specified range and check if it is an even number. If it is even, we add it to the sum variable. Lastly, we output the result of the sum.
By running the above code, the output will be the total sum of even numbers: 30, which means the sum of even numbers between 1 and 10 is 30.