Java:冒号(:)运算符是做什么的? [英] Java: What does the colon (:) operator do?

查看:536
本文介绍了Java:冒号(:)运算符是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会自己去看,但是我甚至不知道它叫什么。有人会介意解释它做什么?



我不知道有多少次出现。在这种情况下,它在这里做了什么:

  public String toString(){
String cardString =; (PlayingCard c:this.list)的
//< -
{
cardString = cardString + c +\\\
;

$ / code $ / pre

你怎么写这个 code>循环不同的方式,以便不纳入:?

解决方案

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

<1>跳出标签(
$ p $ label:for(int i = 0; (int(i,j)){
if(something(i,j))break label; //跳出i循环
}
}
// ie跳转到这里

2)三元条件(教程 ):

  int a =(b <4)? 7:8; //如果b < 4,设a为7,否则设a为8 



3)对于每个循环(教程):

  String [] ss = {hi,there} 
for(String s:ss){
print(s); //在下一次迭代中输出hi和there
}

4 )声明(指南):

  int a = factorial(b); 
声明一个> = 0:阶乘不得小于0;如果条件计算结果为false,则抛出一个AssertionError消息

5)switch语句中的case 教程):

  switch(type){
case WHITESPACE:
case返回:
break;
case NUMBER:
print(got number:+ value);
break;
默认值:
print(syntax error);





6)方法引用(
  class Person {
public static int compareByAge(Person a,Person b){
return a.birthday.compareTo(b.birthday);
}}
}

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


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);

这篇关于Java:冒号(:)运算符是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆