簡體   English   中英

冒號(:)運算符做什么?

[英]What does the colon (:) operator do?

顯然,Java中冒號以多種方式使用。 有人介意解釋它的作用嗎?

例如在這里:

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

您將如何以不同的方式編寫此for-each循環,以便不包含:

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)每個循環( 教程 ):

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

沒有“冒號”運算符,但冒號出現在兩個位置:

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

int x = bigInt ? 10000 : 50;

在這種情況下,三元運算符充當表達式的“ if”。 如果bigInt為true,則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”中的每個值。 因此,如果vals包含[10,20.3,30,...],則x在第一次迭代中將為10,在第二次迭代中將為20.3,依此類推。

注意:我說這不是運算符,因為它只是語法。 它本身不能出現在任何給定的表達式中,並且for-each和三元運算符都可能使用冒號。

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

所以

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

應該讀為“對於每個名稱,IN名稱都應...”

您將如何以不同的方式編寫此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";
   }
}

在這種情況下,我應該加上:不是運算符。 根據JLS,運算符在表達式中執行操作,並且for語句中( ... )中的內容不是表達式...。

它在for循環中用於迭代對象列表。

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

將其視為Python for <item> in <list>for <item> in <list>一個。

您通常在三元賦值運算符中看到它;

句法

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

例:

boolean isNegative = number > 0 ? false : true;

在本質上與“其他”等效

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

除了不同海報的例子,

您還可以使用:表示塊的標簽,可以將其與c​​ontinue和break結合使用。

例如:

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

在您的特定情況下,

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

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

因此,如果this.list是集合{“ 2S”,“ 3H”,“ 4S”},那么最后的cardString將是以下字符串:

2S
3H
4S

它將打印字符串“ something”三遍。

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

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

 panel.add(label);             
 }

由於大多數for循環非常相似,因此Java提供了一種捷徑來減少編寫稱為for循環的循環所需的代碼量。

這是每個循環的簡潔示例:

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

在上面的示例中,冒號(:)可以讀為“ in”。 每個循環的總和可以理解為“對於quizGrades中的每個Integer元素(稱為等級),輸出等級的值”。

用於新的簡寫形式for / loop

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

和三元運算符

list.isEmpty() ? true : false;

冒號實際上與?一起存在?

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

等效於:

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

同樣在for每個循環中:

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

從字面上看:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM