for循环-在java中,for元素包含null



这里有一些我想做的sudo代码。

String[] listA = new String { "a1", "a2"}
String[] listB = new String { null}
String[] listC = new String { "c1", "c2"}
for( String a : listA) {
  for( String b : listB) {
    for( String c : listC) {
       if( a!=null) System.out.print( a);
       System.out.print(",");
       if( b!=null) System.out.print(b);
       System.out.print(",");
       if( c!=null) System.out.print(c);
       System.out.println("");
    }
  }
}

我的预期结果是

a1,,c1
a1,,c2
a2,,c1
a2,,c2

但由于listB为null,代码逻辑无法打印出来。我试着检查列表,并使所有可能的逻辑如下。

if( listA != null) {
  for( String a : list A) {
     if( listB !=null) {
        for(String b : listB) {
           if( listC != null) {
           }
           else { 
                ...
           }
        }
     }
     else {
          ....
     }
  }
}
else {
    ...... similar code in here
}

我认为这不是解决这个问题的最佳方法。你知道吗?

您想要的被称为三个集合(列表)的"乘积"。但是,当其中一个列表为空时,它将被一个包含"空元素"的集合所取代

// pseudo code
String[] safeList(String[] list) { if list.length == 0 return {''} else return list; }
// carthesian product with a twist
static void safeProductWithATwist(
    String[] listA, String[] listB, String[] listC) {
    for(String a: safeList(listA)) 
      for(String b: safeList(listB)) 
        for(String c: safeList(listC)) 
          foo(a, b, c);
}

这在java 中是错误的

String[] listA = new String { "a1", "a2"}
String[] listB = new String { null}
String[] listC = new String { "c1", "c2"}

试试这个。这对你有用。

public class prac {
    public static void main(String[] args) {
        String[] listA = {"a1","a2"};
        String[] listB = {null};
        String[] listC = {"c1", "c2"};
for( String a : listA) {
  for( String b : listB) {
    for( String c : listC) {
       if( a!=null) System.out.print( a);
       System.out.print(",");
       if( b!=null) System.out.print(b);
       System.out.print(",");
       if( c!=null) System.out.print(c);
       System.out.println("");
    }
  }
}
    }
}
package Test;
public class Test {
    public static void main(String[] args) {
        String[] listA =  { "a1", "a2"};
        String[] listB =  { null};
        String[] listC = { "c1", "c2"};
        int count = 0;
        for( String a : listA) { //Two time it will enter
          for( String b : listB) {
              count++;
              System.out.println("");
              System.out.println("Count"+count);
              System.out.println("");
            for( String c : listC) {
                System.out.println("");
               if( a!=null)  System.out.print(a);
               System.out.print(",");
               if( b!=null) System.out.print( b);
               System.out.print(",");
               if( c!=null) System.out.print(a);
            }
          }
        }
    }
}

输出

Count1

a1,,a1
a1,,a1
Count2

a2,,a2
a2,,a2

它将进入循环,因为nulllistB中的一个元素。所以它不会打印b,因为您正在检查b!=null。在答案中,代码中的几个错误也得到了纠正。

最新更新