如何计算二维数组中文本字段的数量?

How can I count the number of text fields in a 2-D array?

在这段代码中,我创建了一个包含四个文本字段的二维文本字段数组。我还放入了一个 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(" ");
    }
}

要计算文本字段的数量,您可以尝试这样的操作:

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

您检查数组本身是否为空,而不是元素。此外,您使用 equals 来检查 null,这将抛出 NullPointerException 而不是返回 true,因为 null 无法取消引用。

在 java 8 中,您可以使用 Streams 为您计数:

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