gpt4 book ai didi

java - 冒号(:) operator do?

转载 作者:太空宇宙 更新时间:2023-11-04 14:35:39 29 4
gpt4 key购买 nike

显然,冒号在 Java 中有多种使用方式。有人介意解释一下它的作用吗?

例如这里:

String cardString = "";
for (PlayingCard c : this.list) // <--
{
cardString += c + "\n";
}

您将如何以不同的方式编写此 for-each 循环,以便不合并 :

最佳答案

Java 代码中有几个地方使用了冒号:

1) 跳出标签 ( Tutorial ):

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

2) 三元条件 ( Tutorial ):

int a = (b < 4)? 7: 8; // if b < 4, set a to 7, else set a to 8

3) For-each 循环 ( Tutorial ):

String[] ss = {"hi", "there"}
for (String s: ss) {
print(s); // output "hi" , and "there" on the next iteration
}

4) 断言 ( Guide ):

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

5) switch 语句中的情况 ( Tutorial ):

switch (type) {
case WHITESPACE:
case RETURN:
break;
case NUMBER:
print("got number: " + value);
break;
default:
print("syntax error");
}

6) 方法引用 ( Tutorial )

class Person {
public static int compareByAge(Person a, Person b) {
return a.birthday.compareTo(b.birthday);
}}
}

Arrays.sort(persons, Person::compareByAge);

关于java - 冒号(:) operator do?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25618204/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com