java中的冒号,Java:冒号(:)运算符是做什么的?

I would look it up myself, but I don't even know what it's called. Would anyone mind explaining what it does?

I didn't know there were multiple times the : appeared. What does it do in this case here:

public String toString() {

String cardString = "";

for (PlayingCard c : this.list) //

{

cardString = cardString + c + "\n";

}

How would you write this for-each loop a different way so as to not incorporate the ":"?

解决方案

There are several places colon is used in Java code:

1) Jump-out label (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) Ternary condition (Tutorial):

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

3) For-each loop (Tutorial):

String[] ss = {"hi", "there"}

for (String s: ss) {

print(s); // output "hi" , and "there" on the next iteration

}

4) Assertion (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) Case in switch statement (Tutorial):

switch (type) {

case WHITESPACE:

case RETURN:

break;

case NUMBER:

print("got number: " + value);

break;

default:

print("syntax error");

}

6) Method references (Tutorial)

class Person {

public static int compareByAge(Person a, Person b) {

return a.birthday.compareTo(b.birthday);

}}

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值