简体   繁体   English

while循环条件说明

[英]Explanation on while loop condition

I have the following code with a while loop in it, However, I am not sure what one part of the while loops does.我有以下代码,其中包含一个 while 循环,但是,我不确定 while 循环的一部分是做什么的。

    int a=nums[i];
    while(i+1<nums.length&&(nums[i+1]-nums[i])==1)
    {
        i++;
    }

I have a nums array and need to create a summary range of it.我有一个 nums 数组,需要创建它的摘要范围。 Can you please explain what the parameters of the while loop mean?你能解释一下while循环的参数是什么意思吗?

There is only one parameter or expression to a while loop: the condition that keeps the loop running if it evaluates to true or ends the loop if it evaluates to false . while循环只有一个参数或表达式:如果计算结果为true则保持循环运行的条件,或者如果计算结果为false则结束循环的条件。 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while . https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while

Given that in the body of the loop, i is being incremented, the code would be better served with a for loop.鉴于在循环体中, i正在递增,代码将更好地使用for循环。 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

The code has a compound condition, both of which must be true for the body of the loop to be executed.代码有一个复合条件,这两个条件都必须为true才能执行循环体。 Both must be true since the boolean AND operator && is used.两者都必须为真,因为使用了 boolean AND 运算符&&

The first condition checks that an OutOfBounds error does not occur by checking that i+1 does not exceed the array nums length and in fact is at most one less the length.第一个条件通过检查i+1不超过数组nums长度并且实际上最多比长度少一个来检查 OutOfBounds 错误是否发生。 The second condition checks that the following element is exactly 1 greater than the current element.第二个条件检查以下元素是否正好比当前元素大 1。

Hope this helps!希望这可以帮助!

1) While index + 1 is less than the nums array length (to prevent OutOfBoundsException for next condition) 1) 虽然 index + 1 小于 nums 数组长度(防止下一个条件出现 OutOfBoundsException)

2) And next element of the array minus the current element of the array equal to one 2) 并且数组的下一个元素减去数组的当前元素等于一

In this while loop there are two conditions connected with && operator.在这个 while 循环中,有两个与&&运算符相关的条件。 so both condition s have to be fullfill.所以两个条件都必须是满的。 In first condition check weather index i+1 is less then to your array size and second depends upon perticular value of index i and i+1 .loop will be continue till both condition satisfied and index will be increase by 1. As soon as one of those condition will be false loop will be terminate.在第一个条件下,检查天气索引i+1小于您的数组大小,第二个取决于索引ii+1的特定值。循环将继续直到满足两个条件并且索引将增加 1。只要一个这些条件将是错误的循环将被终止。 . . You can also use for loop instead of while...it's quite easy to summerise arraylist.您也可以使用 for 循环而不是 while...总结 arraylist 非常容易。 for( int i=0;i<nums.lenght;i++){ nums[i];}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM