简体   繁体   English

Java中具有多个条件的迭代器循环

[英]Iterator loop with multiple conditions in Java

So I'm aware that you can create a for loop with several conditions: 因此,我知道您可以使用几种条件创建一个for循环:

for (int i=0; i<5&&i%2!=1; i++){
//Do something
}

Can the same thing be done in a iterator loop, if so, could an example be given: 是否可以在迭代器循环中完成相同的操作,如果可以,可以给出一个示例:

String[] arrayofstrings = {"Hello", "World"};
for (String s : arrayofstrings){
//Do something
}

No you can't add conditions in the foreach loop. 不,您不能在foreach循环中添加条件。 It can only be used to iterate through the elements. 它只能用于遍历元素。

It can only be like: 它只能像:

for (String s : arrayofstrings){
//Do something
}

and it can't be like: 它不能像:

for (String s : arrayofstrings && some condition){
//Do something
}

Uh, your question is very unclear here. 嗯,您的问题在这里很不清楚。

The first example is a forloop, where the middle section with the conditions is the condition that checks when to stop. 第一个示例是一个forloop,其中带有条件的中间部分是检查何时停止的条件。 Basically, you can think of it as a while loop. 基本上,您可以将其视为while循环。

for(int i = 0; i < 5 && i != 3; i++) {
    doSomething();
}

is the same as 是相同的

int i = 0;
while(i < 5 && i != 3) {
    doSomething();
    i++;
}

The second one just iterates through the items in your list. 第二个只是迭代列表中的项目。 There is no sort of condition... 没有任何条件...

String[] arrayofstrings = {"Hello", "World"};
for(String s : arrayofstrings) {
    System.out.prinltn(s);
}

Will print out 将打印出来

Hello 你好

World 世界

What sort of condition would you want here. 您要在这里什么样的条件。 It is basically the equivalent of doing 基本上等同于

String[] arrayofstrings = {"Hello", "World"};
for(int i = 0; i < arrayofstrings.length; i++) {
    System.out.println(arrayofstrings[i]);
}

There is no condition being evaluated or a time to stop... 没有条件被评估或有时间停止...

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

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