代码之家  ›  专栏  ›  技术社区  ›  dukevin

冒号(:)运算符做什么?

  •  77
  • dukevin  · 技术社区  · 16 年前

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

    例如:

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

    你怎么写这个 for-each 以不同的方式循环,以便不合并 : ?

    12 回复  |  直到 8 年前
        1
  •  172
  •   Randy Sugianto 'Yuku'    10 年前

    在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)对于每个回路( 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语句中的case( 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);
    
        2
  •  34
  •   Claudiu    16 年前

    没有“冒号”运算符,但冒号出现在两个位置:

    1:在三元运算符中,例如:

    int x = bigInt ? 10000 : 50;
    

    在这种情况下,三元运算符充当表达式的“if”。如果bigint为真,那么x将得到10000个赋值。如果不是,50。这里的冒号是“else”的意思。

    2:在for each循环中:

    double[] vals = new double[100];
    //fill x with values
    for (double x : vals) {
        //do something with x
    }
    

    这依次将x设置为“vals”中的每个值。所以如果vals包含[10,20.3,30,…],那么x在第一次迭代中是10,在第二次迭代中是20.3,等等。

    注意:我说它不是运算符,因为它只是语法。它不能单独出现在任何给定的表达式中,而且for-each和三元运算符都有可能使用冒号。

        3
  •  17
  •   helpermethod    16 年前

    只是补充一下,当在for each循环中使用时,“:”基本上可以读作“in”。

    所以

    for (String name : names) {
        // remainder omitted
    }
    

    应该读为“名字中的每个名字都做…”

        4
  •  14
  •   Stephen C    14 年前

    如何为每个循环编写不同的方法,以便不包含“:”?

    假设 list 是一个 Collection 实例…

    public String toString() {
       String cardString = "";
       for (Iterator<PlayingCard> it = this.list.iterator(); it.hasNext(); /**/) {
          PlayingCard c = it.next();
          cardString = cardString + c + "\n";
       }
    }
    

    我应该补充一点迂腐的观点 : 不是此上下文中的运算符。运算符在表达式中执行操作,而 ( ... ) 在一个 for 语句不是表达式…据jls说。

        5
  •  1
  •   Mike Cialowicz    16 年前

    它在for循环中用于遍历对象列表。

    for (Object o: list)
    {
        // o is an element of list here
    }
    

    把它看作 for <item> in <list> 在蟒蛇中。

        6
  •  1
  •   Randy Sugianto 'Yuku'    16 年前

    在你的具体情况下,

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

    this.list 是一个集合(列表、集合或数组),并且该代码指定 c 到集合的每个元素。

    所以,如果 这个列表 是一个集合{“2s”,“3h”,“4s”}然后 cardString 最后是这个字符串:

    2S
    3H
    4S
    
        7
  •  1
  •   ultrajohn    16 年前

    你通常在三元赋值运算符中看到它;

    句法

    variable =  `condition ? result 1 : result 2;`
    

    例子:

    boolean isNegative = number > 0 ? false : true;
    

    在本质上等同于

    if(number > 0){
        isNegative = false;
    }
    else{
        isNegative = true;
    }
    

    除了不同海报上的例子,

    您还可以使用:表示块的标签,可以与“继续”和“打断”一起使用。

    例如:

    public void someFunction(){
         //an infinite loop
         goBackHere: { //label
              for(int i = 0; i < 10 ;i++){
                   if(i == 9 ) continue goBackHere;
              }
         }
    }
    
        8
  •  1
  •   Saurav Sahu    9 年前

    它会把字符串“某物”打印三次。

    JLabel[] labels = {new JLabel(), new JLabel(), new JLabel()};                   
    
    for ( JLabel label : labels )                  
     {              
       label.setText("something");  
    
     panel.add(label);             
     }
    
        9
  •  1
  •   Soft developer    9 年前

    由于大多数for循环非常相似,所以Java提供了一种快捷方式来减少 为每个循环编写调用的循环所需的代码量。

    下面是每个循环的简明示例:

    for (Integer grade : quizGrades){
          System.out.println(grade);
     }    
    

    在上面的例子中,冒号(:)可以读作“in”。for each循环 在 Quizgrades,打印出等级值。”

        10
  •  0
  •   user177800    16 年前

    它用于新的缩写for/loop

    final List<String> list = new ArrayList<String>();
    for (final String s : list)
    {
       System.out.println(s);
    }
    

    三元运算符

    list.isEmpty() ? true : false;
    
        11
  •  0
  •   Ritwik Bose    16 年前

    冒号实际上与 ?

    int minVal = (a < b) ? a : b;
    

    相当于:

    int minval;
    if(a < b){ minval = a;} 
    else{ minval = b; }
    

    在for each循环中:

    for(Node n : List l){ ... }
    

    字面上的:

    for(Node n = l.head; n.next != null; n = n.next)
    
        12
  •  0
  •   Saurabh Srivastava    10 年前

    冒号用于每个循环, 试试这个例子,

    import java.util.*;
    
    class ForEachLoop
    {
           public static void main(String args[])
           {`enter code here`
           Integer[] iray={1,2,3,4,5};
           String[] sray={"ENRIQUE IGLESIAS"};
           printME(iray);
           printME(sray);
    
           }
           public static void printME(Integer[] i)
           {           
                      for(Integer x:i)
                      {
                        System.out.println(x);
                      }
           }
           public static void printME(String[] i)
           {
                       for(String x:i)
                       {
                       System.out.println(x);
                       }
           }
    }