96

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

例如这里:

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

您将如何for-each以不同的方式编写此循环以不包含:?

4

12 回答 12

205

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

2)三元条件(教程):

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

3)for-each循环(教程):

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

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

5)switch语句中的案例(教程):

switch (type) {
    case WHITESPACE:
    case RETURN:
        break;
    case NUMBER:
        print("got number: " + value);
        break;
    default:
        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);
于 2010-03-08T06:16:16.773 回答
34

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

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 和三元运算符都使用冒号只是偶然。

于 2010-03-08T06:12:07.313 回答
21

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

所以

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

应该读作“对于每个名字 IN names do ...”

于 2010-03-08T08:28:54.717 回答
16

您将如何以不同的方式编写此 for-each 循环,以便不包含“:”?

假设这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。

于 2010-03-08T07:27:36.660 回答
1

它在 for 循环中用于迭代对象列表。

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

把它想象成for <item> in <list>Python 中的一个。

于 2010-03-08T06:12:26.280 回答
1

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

句法

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

例子:

boolean isNegative = number > 0 ? false : true;

这在本质上与 if else 是“等价的”

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

除了不同海报给出的例子,

您还可以使用 : 来表示可以与 continue 和 break 结合使用的块标签。

例如:

public void someFunction(){
     //an infinite loop
     goBackHere: { //label
          for(int i = 0; i < 10 ;i++){
               if(i == 9 ) continue goBackHere;
          }
     }
}
于 2010-03-08T06:18:12.560 回答
1

在您的具体情况下,

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

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

所以,如果this.list是一个集合 {"2S", "3H", "4S"} 那么cardString最后就是这个字符串:

2S
3H
4S
于 2010-03-08T06:24:55.083 回答
0

它用于新的简写 for/loop

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

和三元运算符

list.isEmpty() ? true : false;
于 2010-03-08T06:12:01.040 回答
0

冒号实际上与?

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)
于 2010-03-08T06:12:39.073 回答
0

它将打印字符串“something”三次。

JLabel[] labels = {new JLabel(), new JLabel(), new JLabel()};                   

for ( JLabel label : labels )                  
 {              
   label.setText("something");  

 panel.add(label);             
 }
于 2014-07-25T09:30:20.573 回答
0

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

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

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

在上面的示例中,冒号 (:) 可以读作“in”。for each 循环一共可以理解为“对于 quizGrades 中的每个 Integer 元素(称为等级),打印出等级的值”。

于 2017-07-26T03:28:20.533 回答
-1

冒号在 for-each 循环中使用,试试这个例子,

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);
                   }
       }
}
于 2016-10-08T09:11:35.400 回答