用数组java嵌套forloop

时间:2017-02-25 15:53:23

标签: java arrays loops nested

给出一个字符串数组:

    String[] arrays = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N"};

我能够制作模式:

    for(int i = 0; i < 6; i++)
    {
        for(int j = 0; j <= 6; j++)
        { 
            System.out.print(" " + arrays[j]);
        }
        System.out.println();
    }

我理解我的嵌套forloop如何工作为i = 0和j = 0,j会将所有数组索引字母打印到6。 此代码目前创建一个正方形的格式:

     A B C D E F G
     A B C D E F G
     A B C D E F G
     A B C D E F G
     A B C D E F G
     A B C D E F G

但是我想要的是它继续从它停止而不是从之前重复,我知道我需要在嵌套for循环中的某个地方使用if语句,但不确定if语句中包含的内容或它的外观喜欢。 我想要的是什么:

     A B C D E F G
     H I J K L M N

提前谢谢。

4 个答案:

答案 0 :(得分:1)

而不是嵌套的for循环,您可以测试当前索引的模数是array.length的一半是0(即,除法的余数是0) ;如果是打印新行。像,

String[] arrays = { "A", "B", "C", "D", "E", "F", "G", "H", "I", 
                    "J", "K", "L", "M", "N" };
int half = arrays.length / 2;
for (int i = 0; i < arrays.length; i++) {
    System.out.printf("%s ", arrays[i]);
    if ((i + 1) % half == 0) {
        System.out.println();
    }
}

输出(根据要求)

A B C D E F G 
H I J K L M N 

答案 1 :(得分:1)

您可以创建另一个变量来计算总迭代次数,如下所示:

String[][] array = new String[2][7];
int indexKeeper = 0;
String[] arrays = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N"};
for(int i = 0; i<2; i++) {
    for(int j = 0; j<7; j++) {
        array[i][j] = arrays[indexKeeper];
        indexKeeper ++;
        System.out.print(array[i][j]);
    }
    System.out.println();
}

这里是输出

ABCDEFG
HIJKLMN

答案 2 :(得分:0)

int j = 0;
for(int i = 0; i < arrays.length; i++)
{
    j++;
    System.out.print(" " + arrays[i]);
    if (j == 6)
    {
        System.out.println();
        j = 0;
    }
}

答案 3 :(得分:0)

您可以使用while代替for循环

public static void main (String[] args) throws java.lang.Exception
{
    String[] arrays = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N"};
    int i = 0, j = -1;
    while(i < arrays.length) {
        System.out.print(" " + arrays[i]);
        i++;
        j++;
        if(j == 6) {
            System.out.println();
            j = -1;
        } 
    }
}