如何使用带if else语句的数组?

时间:2017-06-02 14:40:54

标签: java arrays if-statement

我有这段代码:

 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 个答案:

答案 0 :(得分:1)

您要打印列标题两次,因为您已将其放在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);
            }
        }
    }
}