如何使用Array和if else语句?

问题描述:

我有这样的代码:如何使用Array和if else语句?

String[] sweetFlevors = { "Caramel", "Cinnamon", "Wetermelon", "Backed Beans" }; 

String[] savoryFlavors = { "Sea Salt", "Potato Chip", "Carrot", "Barbque" }; 

int[] numberRows = { 1, 2, 3, 4 }; 
int[] numberCol = { 1, 2 }; 

for (int col = 0; col < numberCol.length; col++) { 
    System.out.println("  " + numberCol[0] + "   " + numberCol[1]); 

    for (String sweet: sweetFlevors) { 
     for (String savory: savoryFlavors) { 

      for (int row = 0; row < numberRows.length; row++) { 
       System.out.print(numberRows[row] + ". "); 

       System.out.println(sweet + " and " + savory); 
      } 
     } 
    } 
} 

和我的输出是这样的:

1   2 
1. Caramel and Sea Salt 
2. Caramel and Sea Salt 
3. Caramel and Sea Salt 
2. Wetermelon and Carrot 
3. Backed Beans and Barbque 
4. Backed Beans and Barbque 
     1   2  // How to delete this line? 
1. Caramel and Sea Salt 
2. Caramel and Sea Salt 

我不知道我怎么可以删除第二行列?为什么我得到它?

感谢你帮我:)

+1

你问的是真的不清楚。你应该解释你想做什么,你得到什么,并请以可读的方式格式化你的代码。 – davidxxx

+0

我必须练习ARRAY,因此我会做各种各样的代码练习。 – ein

你两次打印的列标题,因为你已经把它的for循环for (int col = 0; col < numberCol.length; col++)内。你必须这样做:

String[] sweetFlevors = { "Caramel", "Cinnamon", "Wetermelon", "Backed Beans" }; 

String[] savoryFlavors = { "Sea Salt", "Potato Chip", "Carrot", "Barbque" }; 

int[] numberRows = { 1, 2, 3, 4 }; 
int[] numberCol = { 1, 2 }; 

System.out.println("  " + numberCol[0] + "   " + numberCol[1]); 
for (int col = 0; col < numberCol.length; col++) { 
    for (String sweet: sweetFlevors) { 
     for (String savory: savoryFlavors) { 
      for (int row = 0; row < numberRows.length; row++) { 
       System.out.print(numberRows[row] + ". "); 

       System.out.println(sweet + " and " + savory); 
      } 
     } 
    } 
} 
+0

非常感谢你!现在它对我工作:) .. – ein