2010-03-08 559 views
70

我會自己查看它,但我甚至不知道它叫什麼。有人會介意解釋它的作用嗎?Java:冒號(:)運算符的作用是什麼?

我不知道有多次:出現了。它有什麼作用在這種情況下,在這裏:

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

你會如何寫這for-each循環以不同的方式,以不納入「:」?

+4

其他人已經提到這種情況是for-each循環。有關它如何工作的更詳細的解釋,請參閱http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html – Jonik 2010-03-08 06:31:52

回答

160

有幾個地方結腸中的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 loop(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); 
+3

不錯 - 我錯過了一些!而我甚至不知道你可以這樣命名斷言,非常有用。 – Claudiu 2010-03-08 06:22:52

+0

來自.NET(C#),所討論的結構的最接近的比喻是for-each,這是你以良好的方式解釋的。 – Roger 2012-09-06 07:41:38

+1

失敗的'assert'不會「退出程序」。它拋出一個'AssertionError'。它只會導致程序退出,如果它被扔在唯一剩下的非守護線程的堆棧上,並且沒有被捕獲。 – 2014-06-13 08:09:57

0

它是在新的短手用於/循環

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

和三元運營商

list.isEmpty() ? true : false; 
+0

我沒有意識到它是新的...當它進來了嗎? – 2010-03-08 06:17:36

+0

@Mechko,在Java 5中:http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#forloop – Jonik 2010-03-08 06:26:55

+3

哦...那是6年前...不是新的我的參考框架:D – 2010-03-08 06:40:29

33

沒有「冒號」操作,但結腸出現在兩個地方:

1:在三元運算符,例如:

int x = bigInt ? 10000 : 50; 

在這種情況下,三元運算符充當表達式的'if'。如果bigInt是真的,那麼x將得到10000分配給它。如果沒有,50.這裏的冒號意思是「其他」。

2:在for-each循環:

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

這設置x到各值中依次 '瓦爾斯'。因此,如果vals包含[10,20.3,30,...],那麼在第一次迭代中x將爲10,第二次爲20.3等。

注意:我說它不是運算符,因爲它只是語法。它本身不能出現在任何給定的表達式中,這只是偶然的,for-each和ternary操作符都使用冒號。

+0

下半年的幫助,這應該是真正的答案 – erp 2014-08-14 15:59:34

+0

+ 1的更詳細的解釋,它爲每個循環做什麼。 – dfarrell07 2014-09-15 18:05:19

1

它用在for循環遍歷對象的列表。

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

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

0

結腸實際上結合存在具有?

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

相當於:

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

此外,在每個循環:

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

字面上:

for(Node n = l.head; n.next != null; n = n.next) 
1

你通常在三元賦值操作符中看到它;

語法

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

例如:

boolean isNegative = number > 0 ? false : true; 

在本質上是 「等價於」 如果別人

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

除了由不同的海報給出的例子,

你可以n您還可以使用:來表示,而您可以在繼續,並打破一起使用塊標籤..

例如:

public void someFunction(){ 
    //an infinite loop 
    goBackHere: { //label 
      for(int i = 0; i < 10 ;i++){ 
       if(i == 9) continue goBackHere; 
      } 
    } 
} 
+2

對不起,但這是一個可怕的例子。爲什麼你不寫 boolean isNegative = number> 0; 三元條件適用於諸如 double sgn = number> 0的情況。 1:0; – user44242 2010-03-08 07:48:02

+0

@ user44242 lol是的,我甚至不記得爲什麼我給了這個例子。 – ultrajohn 2015-12-31 12:17:27

1

在特定情況下,

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

this.list是一個集合(列表,集合或數組),並且該代碼將c分配給集合的每個元素。

所以,如果this.list是一個集合{ 「2S」, 「3H」, 「4S」}然後在年底cardString將這個字符串:

2S 
3H 
4S 
+1

感謝您的回答。這段代碼如何被重寫爲不使用「:」? – dukevin 2010-03-08 06:31:47

14

你會如何寫這爲 - 每個循環都有不同的方式,以便不包含「:」?

假設listCollection實例...

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

我要補充的迂腐點:是不是在這種情況下操作。一個操作符在一個表達式中執行操作,根據JLS,for語句中的(...)內部的內容不是表達式。

+0

我的問題是:爲什麼?爲什麼要做同樣的事情呢? – RichN 2010-03-08 14:49:09

+2

@RichN - 他不想這樣做,他只是想知道如何。 – 2010-03-08 14:57:57

+3

不作業,我想知道如何做到這一點,所以我可以理解邏輯 – dukevin 2011-02-09 21:03:10

16

只需添加,當在for-each循環中使用時,「:」基本上可以讀作「in」。

所以

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

應讀「IN名對於每一個名字做......」

1

它將打印字符串「某物」三次。

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

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

panel.add(label);    
} 
+1

這就是上面所說的ForEach循環 – 2015-03-20 06:14:36

0

結腸使用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); 
        } 
     } 
} 
1

由於大多數for循環是非常相似的,Java提供一個捷徑,以減少寫所需的 量的代碼該循環稱爲每個循環。

這裏是簡明的每個循環的示例:

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

在上面的例子中,冒號(:)可以讀作「在」。對於每個循環 共計可讀作「爲 中的每個Integer元素(稱爲等級)測驗格式,打印出等級值。」