gpt4 book ai didi

java - 如何使用循环对偶数求和

转载 作者:行者123 更新时间:2023-12-03 11:17:35 25 4
gpt4 key购买 nike

我需要有关此代码的帮助我似乎在对偶数求和时遇到问题,我想要发生的是偶数将被输出,同时会有一个输出,其中所有偶数都在其中求和用户输入的范围。我只是编码的初学者,我希望有人可以帮助我。

import java.util.*;
public class Loop
{
//Start
public static void main(String args[])
{

Scanner console = new Scanner(System.in) ;
System.out.println("Enter Start Number") ;
int start =console.nextInt();
System.out.println("Enter End Number") ;
int end =console.nextInt();

int sum = 0;
System.out.println("The even numbers between "+start+" and "+end+" are the following: ");
for (int r = start; r <= end; r++)
{
//if number%2 == 0 it means its an even number
if(r % 2 == 0)
{
System.out.println(r);
}
}
}
}

最佳答案

一种使用 Java 流的简洁方法。把它放在这里,这样你就知道还有另一种方法可以做到这一点:

int sum = IntStream.range(start, 1 + end).filter(num -> 0 == num % 2).peek(System.out::println).sum();
System.out.println(sum);

关于java - 如何使用循环对偶数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64404472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com