忽略循环遍历数组时的空值。

huangapple go评论77阅读模式
英文:

Ignore null value while looping through an array

问题

我正在构建一个方法,该方法从我的数组中打印出特定的值。问题是,数组中的每个值都由构造函数给出多个值,因此数组看起来像这样:

Constructor1[] tab1 = {new Constructor1 (var1: 1, var2: 3, var3: "Hi"),
                     null,
                     new Constructor1 (var1: 3, var2: 2, var3: "Ho"),
                     null}...

null 值对应于我构造函数的空实例,我不想删除它们。当我遍历数组时,我使用另一个类中构建的 getter 来获取特定的值。

for (int i = 0, i<= tab1.length, i++) {
    if (tab[i].getVar2() == 2){
    System.out.print(tab[i]);
    }
}

我可以正确地将值打印出来,直到遍历到 null,这会停止我的程序。我的程序目标是从数组中提取某些内容并将它们保存到文件中,但由于 null,我无法提取我想要的所有内容。为了这个项目,我使用 FileReader、PrintReader 等等...

英文:

I'm building a method which prints certain specific values from my array. The thing is, each value from that array has multiple values given by a constructor so the array looks like this :

Constructor1[] tab1 = {new Constructor1 (var1: 1, var2: 3, var3: &quot;Hi&quot;),
                     null,
                     new Constructor1 (var1: 3, var2: 2, var3: &quot;Ho&quot;),
                     null}...

The null values correspond to empty instances of my constructor and I do not want to delete them. When I loop through my array I use a getter I built in another class to get the specific value.

for (int i = 0, i&lt;= tab1.length, i++) {
    if (tab[i].getVar2() == 2){
    System.out.print(tab[i]);
    }
}

I can get the values to print right until I loop through null, which stops my program. The goal to my program is to extract certain things from the array and save them onto a file, but I cant extract everything I want because of null. For the purpose of this project I use FileReader, PrintReader etc...

答案1

得分: 2

以下是您要翻译的内容:

添加一个空值检查:

for (int i = 0; i <= tab1.length; i++) {
    if (tab[i] != null && tab[i].getVar2() == 2) {
        System.out.print(tab[i]);
    }
}
英文:

Put a null check

for (int i = 0, i&lt;= tab1.length, i++) {
	if (tab[i]!=null &amp;&amp;tab[i].getVar2() == 2){
	System.out.print(tab[i]);
	}
}

huangapple
  • 本文由 发表于 2020年5月5日 08:56:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/61604054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定