duk*_*vin 82 java foreach for-loop operators colon
显然,在Java中以多种方式使用冒号.有人会介意解释它的作用吗?
比如这里:
String cardString = "";
for (PlayingCard c : this.list) // <--
{
cardString += c + "\n";
}
Run Code Online (Sandbox Code Playgroud)
你会如何for-each
以不同的方式编写这个循环,以便不包含:
?
Ran*_*ku' 182
在Java代码中使用冒号有几个地方:
1)跳出标签(教程):
label: for (int i = 0; i < x; i++) {
for (int j = 0; j < i; j++) {
if (something(i, j)) break label; // jumps out of the i loop
}
}
// i.e. jumps to here
Run Code Online (Sandbox Code Playgroud)
2)三元条件(教程):
int a = (b < 4)? 7: 8; // if b < 4, set a to 7, else set a to 8
Run Code Online (Sandbox Code Playgroud)
3)For-each循环(教程):
String[] ss = {"hi", "there"}
for (String s: ss) {
print(s); // output "hi" , and "there" on the next iteration
}
Run Code Online (Sandbox Code Playgroud)
4)断言(指南):
int a = factorial(b);
assert a >= 0: "factorial may not be less than 0"; // throws an AssertionError with the message if the condition evaluates to false
Run Code Online (Sandbox Code Playgroud)
5)switch语句中的案例(教程):
switch (type) {
case WHITESPACE:
case RETURN:
break;
case NUMBER:
print("got number: " + value);
break;
default:
print("syntax error");
}
Run Code Online (Sandbox Code Playgroud)
6)方法参考(教程)
class Person {
public static int compareByAge(Person a, Person b) {
return a.birthday.compareTo(b.birthday);
}}
}
Arrays.sort(persons, Person::compareByAge);
Run Code Online (Sandbox Code Playgroud)
Cla*_*diu 34
没有"冒号"运算符,但冒号出现在两个地方:
1:在三元运算符中,例如:
int x = bigInt ? 10000 : 50;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,三元运算符充当表达式的"if".如果bigInt为true,则x将为其分配10000.如果没有,50.这里的冒号意味着"别的".
2:在for-each循环中:
double[] vals = new double[100];
//fill x with values
for (double x : vals) {
//do something with x
}
Run Code Online (Sandbox Code Playgroud)
这依次将x设置为'vals'中的每个值.因此,如果val包含[10,20.3,30,...],那么x将在第一次迭代时为10,在第二次迭代时为20.3,等等.
注意:我说它不是运算符,因为它只是语法.它本身不能出现在任何给定的表达式中,并且只有for-each和三元运算符都使用冒号的机会.
hel*_*hod 18
只是要添加,当在for-each循环中使用时,":"基本上可以读作"in".
所以
for (String name : names) {
// remainder omitted
}
Run Code Online (Sandbox Code Playgroud)
应该读"为每个名字IN名称做..."
Ste*_*n C 15
你怎么用不同的方式为每个循环写这个,以便不包含":"?
假设这list
是一个Collection
实例......
public String toString() {
String cardString = "";
for (Iterator<PlayingCard> it = this.list.iterator(); it.hasNext(); /**/) {
PlayingCard c = it.next();
cardString = cardString + c + "\n";
}
}
Run Code Online (Sandbox Code Playgroud)
我应该:
在这种情况下添加一个不是运算符的迂腐点.操作员在一个表达式执行操作,并且里面的东西( ... )
的for
语句不是一种表达......根据JLS.