使用布尔值来控制do / while循环

时间:2015-11-18 20:41:54

标签: loops boolean do-while

我是初学程序员,第一次学习基础知识。我正在尝试编写一个程序,只要布尔值为假,就可以计算数字的总和。

这是我的代码:

public class BooleanSum
{
    int count = 0;
    int total = 0;
    boolean cond = false;
do
{
    ++count;
    total = total + count;
    if (count >= 100)
    {
        cond = true;
    }
} while (cond);
System.out.println(total);

这是我的输出: 1

我正在寻找的输出是5050,因为这是正确的总和。

我做错了什么?

4 个答案:

答案 0 :(得分:1)

首先,您的代码逻辑应位于函数内,并且可能位于Main()函数内,并且在您的情况下问题出现在下面的代码块中

if (count >= 100)
{
    cond = true;
}

哪个应该是

while (count >= 100);

答案 1 :(得分:1)

只需将整个代码放在main函数中,然后将“while(cond)”更改为“while(!cond)”。在你的代码中,内部条件为false,这就是代码只执行一次然后退出循环的原因。这就是你得到1的原因。

答案 2 :(得分:0)

int total = 0;

for ( int count = 1; count <= 100; count++ )
  total += count;

看起来更简单。

答案 3 :(得分:0)

The problem is the boolean - just make a switch of it

 public class BooleanSum {

  public static void main(String[] args) {

    int count = 0;
    int total = 0;
    boolean cond = true;
    do {

        total = total + count;
        if (count >= 100) {
            cond = false;
        }
        count++;
    } while (cond);

    System.out.println(total);

 }
}