Topic: 用do...while为何只循环一次

  Print this page

1.用do...while为何只循环一次 Copy to clipboard
Posted by: 吕海鹏
Posted on: 2005-12-11 10:00

我用do...while循环
方法一
class A
{
  public static void main(String[] args)
  {
    int n = 10;
    do
      {
      System.out.println(n);
      n--;
      } while(n > 0);

  }
}
正常,为什么我将判断 改成 while(n==0)只循环一次

2.Re:用do...while为何只循环一次 [Re: 吕海鹏] Copy to clipboard
Posted by: ranchgirl
Posted on: 2005-12-11 10:26

Read any Basic Java book, read the loop section, you will get your own answer...

Pay attention to what loop condition means...


do {
// do something here
// the loop condition may change here
} while (loop_boolean_condition)

3.Re:用do...while为何只循环一次 [Re: 吕海鹏] Copy to clipboard
Posted by: tkzyxtxn
Posted on: 2005-12-11 10:27

do...while的执行顺序是先执行后校验,n--后,n为一个固定值,执行循环体后,进行循环条件校验,不符合就会跳出循环。
在此程序中若循环条件为n==9,循环会执行两次,其余为一次。

4.Re:用do...while为何只循环一次 [Re: 吕海鹏] Copy to clipboard
Posted by: 吕海鹏
Posted on: 2005-12-11 10:30

废话,书中有还问

5.Re:用do...while为何只循环一次 [Re: tkzyxtxn] Copy to clipboard
Posted by: 吕海鹏
Posted on: 2005-12-11 10:38

tkzyxtxn wrote:
do...while的葱兴承蚴窍戎葱泻笮Q椋琻--后,n为一个固定值,执行循环体后,进行循环条件校验,不符合就会跳出循环。
在此程序中若循环条件为n==9,循环会执行两次,其余为一次。


谢谢,我测试了循环条件为n==9,循环会执行两次,关键就是为什么,其余为一次,没太转过弯来

6.Re:用do...while为何只循环一次 [Re: 吕海鹏] Copy to clipboard
Posted by: ranchgirl
Posted on: 2005-12-11 10:43

You probably don't understand what n-- means.


n--;
// which is equivalent to n = n -1;
// n was 10, after executing once, it is 9...

7.Re:用do...while为何只循环一次 [Re: 吕海鹏] Copy to clipboard
Posted by: ranchgirl
Posted on: 2005-12-11 10:49

To Why:

I am practicing what you said, hehe Smile even no matter how rude s/he is.

why wrote:
gongshi:

usually I'll try to help every newcomer once, no matter how lazy s/he is.
I'll consider zero-tolerance.Sad

8.Re:用do...while为何只循环一次 [Re: 吕海鹏] Copy to clipboard
Posted by: yangyuming
Posted on: 2005-12-11 15:44

n--后n的值为9,所以n==9为false,所以不再执行了.

9.Re:用do...while为何只循环一次 [Re: 吕海鹏] Copy to clipboard
Posted by: 吕海鹏
Posted on: 2005-12-11 20:21

下午已经弄懂了,,根本就不是n--的问题,是while判断的问题,while(n==0)时,为false,自然就不执行;所以应该为while(!(n==0)),即n不等于0时为true,程序循环,
代码如下:

class A
{
public static void main(String[] args)
{
int n = 10;
do
{
System.out.println(n);
n--;
} while(!(n==0));

}
}

10.Re:用do...while为何只循环一次 [Re: 吕海鹏] Copy to clipboard
Posted by: sz_ren
Posted on: 2005-12-14 19:35

晕,搞得这么复杂干什么呢?你换成n!=0不也一样嘛!只要n不等于0都回进入循环。


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923