使用Java中的while循环来找到0和给定整数之间所有数字的总和如何?

huangapple go评论71阅读模式
英文:

How can I use a while loop in java to find the sum of all numbers between 0 and a given integer?

问题

I'm happy to join the community. I have no prior experience in coding, and I am currently taking my very first steps into Java programming. Can someone please help me understand and solve the problem in the labs about loops in Java? Please find attached the screenshots of the labs. Thank you for helping.

Loops in Java and here.

What is the code for a while loop to get the sum of all numbers between 0 and "end" (exclusive)?

英文:

I'am happy to join the community. I have no prior experience to coding and I am currently experiencing my very first steps into java programming. Can someone please help me understand and solve the problem in the labs about the loop in java. Please find attached the screenshots of the labs.
Thank you for helping[Loops in java](https://i.stack.imgur.com/7FkEL.png)

What is the code for a while loop to get the sum of all numbers between 0 and end (exclusive)

答案1

得分: -1

请注意,你的_while循环_被注释掉了。

这是关于_while_和_do-while_循环的Java教程。
while和do-while语句(Java™教程 > 学习Java语言 > 语言基础)

在Java中,要创建一个while循环,你可以使用以下结构。

while (i < end) {

}

要计算从_i_到不包括_end_的值的总和,你可以使用以下代码。

sum = sum + i;
i = i + 1;

要返回_sum_的值,你可以使用以下代码

return sum;

总之,_whileExample_方法的完整代码如下。

int whileExample(int end) {
    int sum = 0;
    int i = 0;
    while (i < end) {
        sum = sum + i;
        i = i + 1;
    }
    return sum;
}
英文:

Note that your while-loop is commented-out.

Here is a Java tutorial on while and do-while loops.
The while and do-while Statements (The Java™ Tutorials > Learning the Java Language &gt; Language Basics).

In Java, to create a while-loop, you use the following structure.

while (i &lt; end) {

}

To derive a sum of values, from i to an exclusive end, you can use the following.

sum = sum + i;
i = i + 1;

To return the sum value, you use

return sum;

All together the code for the whileExample method would be as follows.

int whileExample(int end) {
    int sum = 0;
    int i = 0;
    while (i &lt; end) {
        sum = sum + i;
        i = i + 1;
    }
    return sum;
}

huangapple
  • 本文由 发表于 2023年5月29日 10:21:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定