【问题标题】:Variable initialized inside do{} is not incrementing在 do{} 中初始化的变量不递增
【发布时间】:2017-01-31 22:04:42
【问题描述】:

只是为了练习,我试图在两种不同的场景中运行以下代码,最初我认为它们都可以工作,但是当我运行程序时,一个有效,一个无效,这是有效的代码

public class Test1
{
   public static void main(String args[])
   {

    int counter = 0; 
    int number = 1;
    do{ 
        System.out.println(number);
        number++; 
        counter++; 
    }while(counter<20);
}  }

O/P : 1 2 3 ... {最多打印 19 个}

这是一个没用的

 public class Test2
{
   public static void main(String args[])
   {
    int counter = 0; 
    do{ 
        int data = 0; 
        System.out.println(data);
        data++; 
        counter++; 
    }while(counter<20);
}  }

O/P : 0 0 0 0 ...{最多打印 19 次 }

【问题讨论】:

  • 嗯,是的,您在循环的每次迭代开始时将data 初始化为0。目前尚不清楚为什么您会 expect 打印其他任何内容。每次迭代实际上都有一个单独的data 变量。如果您不希望这样,请根据您的第一段代码在循环外声明并初始化它...
  • @JonSkeet 知道了,我知道我不应该只是在尝试,但没想到!!

标签: java scope initialization


【解决方案1】:

因为在每次迭代中,您的数据字段将首先设置为 0,然后您打印它,然后 ++ 它

public class Test2
    {
       public static void main(String args[])
       {
        int counter = 0; 
        do{ 
           int data = 0; // declare a new data field and initialize to 0
           System.out.println(data); // display zero
           data++; // data now is 1
           counter++; 
        }while(counter<20);
      } 
   }

【讨论】:

    【解决方案2】:

    输出是正确的,因为数据variable在每次迭代中都被初始化为0

     public class Test2
        {
           public static void main(String args[])
           {
            int counter = 0; 
            do{ 
                int data = 0; System.out.println(data); data++; counter++; 
            }while(counter<20);
        }  }
    

    考虑 do .. while 循环

    假设第一次迭代

    1.int data = 0; // data will be 0 
    2.System.out.println(data); // prints 0
    3.data++;//Incrementing the data to 1
    4.counter ++;// incrementing the counter to 1 
    

    第二次迭代

    1.int data = 0; // data will be again set to  0 
    2.System.out.println(data); // prints 0
    3.data++;//Incrementing the data to 1
    4.counter ++;// incrementing the counter to 2
    

    所以输出将是数据 0,0,0............ 而计数器将是 1,2,......

    数据的范围将是本地的并且每次都重新初始化,为了避免这个问题,你应该像在第一个代码示例中那样使变量脱离循环

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多