Java循环未达到停止条件程序结束

时间:2017-06-14 19:57:57

标签: java loops while-loop

程序从另一个类调用一个方法,它有助于改变程序的停止条件。它平均调用该方法约3-8次,并且永远不会达到停止状态,但它会停止。

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

       Example ex = new Example();
       long [] result;

       long a = 0;
       long b = 0;
       long c = 0;
       long d = 0;
       long e = 0;
       int count = 0;

       int a1 = 1;
       int b1 = 2;
       int c1 = 3;
       int d1 = 4;
       int e1 = 5;


      for(int i = 0; i <1; i++)
      {
        while(a != a1 && b != b1 && c != c1 && d != d1 && e != e1)
        {
          result = ex.getOnes();
          a = result[0];
          b = result[1];
          c = result[2];
          d = result[3];
          e = result[4];

          System.out.println(result[0] + " " + result[1] + " " + result[2] + " " + result[3] + " " + result[4]);

        System.out.println(a + " " + b + " " + c + " " + d + " " + e + " " + count++);

        }
       System.out.println(a + " " + b + " " + c + " " + d + " " + e + " "+ count);

      }



     }
   }

Example类如下:

import java.util.*;

public class Example 
{
  Random r = new Random();

    public long[] getOnes(){

        int a = r.nextInt(35);
        int b = r.nextInt(35);
        int c = r.nextInt(35);
        int d = r.nextInt(35);
        int e = r.nextInt(35);

        while(a == 0)
        {
            a = r.nextInt(35);
            //temp[0] = a;
        }

        while(b == 0 || b == a /*|| b == c || b == d || b == e*/)
        {
            b = r.nextInt(35);
            //temp[1] = b;
        }

        while(c == 0 || c == a || c == b /*|| c == d || c == e*/)
        {
            c = r.nextInt(35);
            //temp[2] = c;
        }

        while(d == 0 || d == a || d == b || d == c/*|| d == e*/)
        {
            d = r.nextInt(35);
            //temp[3] = d;
        }

        while(e == 0 || e == a || e == b || e == c|| e == d)
        {
            e = r.nextInt(35);
            //temp[4] = e;
        }

        return new long[] {a, b, c, d, e};
    }

}

useExample类的while循环只应在while的每个condtion为false时停止。这意味着何时:

a == a1
b == b1 
c == c1 
d == d1 
e == e1

它应该输出它经过的循环次数和每个循环的值。最终输出相同的a1到e1的值。

2 个答案:

答案 0 :(得分:1)

  

useExample类的while循环应该只在每个循环时停止   对此的判断是错误的。这意味着何时:

a == a1
b == b1 
c == c1 
d == d1 
e == e1

然后你的while循环现在错了,应该是这样的:

while (a != a1 || b != b1 || c != c1 || d != d1 || e != e1)

因为while包含的条件不是when to stop而是when to continue

答案 1 :(得分:0)

只要满足其中一个条件,while循环就会结束。如果您想要满足所有条件,请使用||而不是&amp;&amp;。