在Java中是否可以使用类似(i++,++i)的语法来表示布尔逻辑运算符?
我有一个布尔变量,仅对foreach循环的第一次迭代才为真.必须跳过那次迭代.
完整的语法是
for (...)
{
if (bool)
{
bool &= false;
continue;
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有任何方法可以缩短语法而不使用AtomicBoolean.例如,构造if (bool &= false)在语法上是正确的,但我认为它将比较最终结果而不是原始值.
谷歌不是我的朋友,因为搜索查询具有误导性
Jon*_*eet 51
就个人而言,我会将您当前的代码简化为:
for (...)
{
if (bool)
{
bool = false;
continue;
}
// Rest of code
}
Run Code Online (Sandbox Code Playgroud)
...但如果你真的想在if副作用的条件下这样做,你可以使用:
for (...)
{
if (bool && !(bool = false))
{
continue;
}
// Rest of code
}
Run Code Online (Sandbox Code Playgroud)
这里操作&&符的第一个操作数涵盖后续操作,并!(bool = false)始终计算true 并设置bool为false.
另一种选择,来自评论:
for (...)
{
if (bool | (bool = false))
{
continue;
}
// Rest of code
}
Run Code Online (Sandbox Code Playgroud)
这会在每次迭代时执行赋值,但每次都会给出正确的结果.
我真的,真的不会使用这两个选项中的任何一个.
Pet*_*ček 22
你的代码是通常的事情.但是,还有另一种选择:
for (SomeType thing : Iterables.skip(things, 1)) {
// process thing
}
Run Code Online (Sandbox Code Playgroud)
这使用了Google Guava的Iterables.skip()方法并产生了您期望的输出 - 每个循环遍历集合并跳过第一个元素.
或者,只需使用整数变量并使用++后递增.
int iter = 0;
for (...) {
if (iter++ == 0) {
continue;
}
...
}
Run Code Online (Sandbox Code Playgroud)
如果您想跳过第一次迭代,这可能更容易理解.
不要对布尔类型使用增量如果必须使用布尔值,要么切换它,例如!bool,或者只是将其设置为false:
for (...){
if (bool) {
bool = false;
continue;
}
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,如果你想要的是跳过第一个,最后一个或第n个迭代,那么除了int之外不要使用布尔值...
int skipIndex = 0;
for(int index=0; index < 5; index++){
if(index != skipIndex) {
System.out.println(index);
}
}
Run Code Online (Sandbox Code Playgroud)
...或以下内容仅跳过第一次迭代:
int[] values = new int[]{0, 1, 2, 3, 4};
for (int index = 1; index < values.length; index++) {
System.out.println(values[index]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2495 次 |
| 最近记录: |