2016-11-18 98 views
0

在此代碼中,我創建了一個包含四個文本字段的文本字段的二維數組。我還輸入了一個if語句來檢查此數組是否爲null。但我想要統計這個數組中有多少文本字段?如何計算二維數組中的文本字段數?

@FXML private TextField f00; 
@FXML private TextField f01; 
@FXML private TextField f10; 
@FXML private TextField f11; 

TextField txt[][] = new TextField [2][2] ; //the array of textfields 

@FXML public void cell() { 
    txt[0][0] = f00; 
    txt[0][1] = f01; 
    txt[1][0] = f10; 
    txt[1][1] = f11; 

    for (int i = 0; i<txt.length; i++) {// loop for rows 
     for (int j =0; j< txt[0].length; j++) { // loop for columns 
      if(!txt.equals(null)) { // if this array isn't null/ empty! 
       System.out.println(txt[i][j]); // print what inside this array if the array not null 
      } 
     System.out.println(" "); 
    } 
} 
+0

我曾試圖彌補與當計數器循環,但它不工作! –

+0

我wan to地問,在相同的代碼中,如果我可以創建或創建一個計數器,可以統計多少文本字段爲空並且有多少文本字段不爲空 –

回答

0

要計算文本字段的數量,你可以嘗試這樣的事:

int count = 0; 
for (int i = 0; i < txt.length; i++) { 
    for (int j = 0; j < txt[i].length; j++) { 
     if (txt[i][j] != null) { 
      count++ 
     } 
    } 
} 
System.out.println("Number of text fields: " + count); 
+0

感謝那正是我想要的 –

0

您檢查數組本身無效,而不是元素。此外,您使用equals來檢查null,這將拋出NullPointerException而不是返回true,因爲null不能被取消引用。

在java中8,您可以使用Streams做計數爲您提供:

long count = Stream.of(txt).flatMap(Stream::of).filter(Objects::nonNull).count(); 
+0

就像發生在第一次之後編寫代碼。當我運行該程序時,它直接引發異常。但感謝您的通知 –