插入|打印数组时每2个字符

时间:2018-05-06 19:02:28

标签: java arrays

我的问题是,我有一个int数组,我试图以某种方式打印。我有一个21个整数的int数组。目前,当我打印数组时,我得到了

[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0]

但是,当我打印

时,我希望它看起来像这样
|10, 10| 10, 10| 10, 10| 10, 10| 10, 10| 10, 10| 0, 0| 0, 0| 0, 0| 0, 0| 0

我试过像这样的for循环

for(int i = 0; i < game.getRolls().length; i += 2) {
    String sep = "|"
    System.out.print(sep);
    System.out.print(game.getRolls()[i]);
}   

但所有这一切都是用|替换所有其他数字。有没有办法改变逗号? 谢谢!

4 个答案:

答案 0 :(得分:2)

for(int i = 0; i < game.getRolls().length; i ++)
{
    String sep = "|";
    if(i%2 == 0){
       System.out.print(sep);
    }
    else{
       System.out.print(",");
    }
    System.out.print(game.getRolls()[i]);
} 

答案 1 :(得分:0)

我会将数组保存为局部变量。接下来,迭代和打印对(虽然至少有两个元素,我会使用格式化的io)。然后检查循环后是否还有元素,如果是则打印它。像,

int[] rolls = { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 
        0, 0, 0, 0, 0, 0, 0, 0, 0 };
int i = 0;
for (; i < rolls.length - 1; i += 2) {
    System.out.printf("| %d, %d ", rolls[i], rolls[i + 1]);
}
if (i < rolls.length) {
    System.out.printf("| %d", rolls[rolls.length - 1]);
}
System.out.println();

答案 2 :(得分:0)

这是一个结合了@ user9749556和@MạnhQuyếtNguyễn的答案的解决方案:

for (int i = 0; i < array.length; i++) {
    int item = array[i];

    if (i == array.length - 1) { // The last item
        System.out.print(item);
    } else {
        if ((i + 1) % 2 == 0) {
            System.out.print(item + " | ");
        } else { // The index is odd
            System.out.print(item + ", "); 
        }
    }
}

System.out.println();

测试用例:

array = {1, 2, 3, 4, 5}; // prints "1, 2 | 3, 4 | 5"
array = {1, 2, 4, 8}; // prints "1, 2 | 4, 8"
array = {}; // prints ""

Here's a link to the full, working code.

答案 3 :(得分:0)

对于lolz,因为答案已被接受。 但我认为这个解决方案更容易阅读...

int[] rolls = { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (int i = 0 ; i < rolls.length ; i++) {
    System.out.print(i % 2 == 0 ? "| " : ", ");
    System.out.print(rolls[i] + " ");
}
System.out.print("|");
// output : | 10 , 10 | 10 , 10 | 10 , 10 | 10 , 10 | 10 , 10 | 10 , 10 | 0 , 0 | 0 , 0 | 0 , 0 | 0 , 0 | 0 |

<强> Demo