从其他方法打印ArrayList

时间:2015-11-24 19:41:15

标签: java arraylist printf

设计一个功能,其职责是很好地显示素数数组。它应该每行显示数组10的内容。需要打印和打印的组合。显示每个 宽度为7的字段中的数字(使用printf)。

这就是我所拥有的,但我不确定是否正确。

public  static void printArray(ArrayList<Integer> primes){
    System.out.printf("%7s", primes);
    if (prrimeCount % 10 == 0){
        System.out.println();
    }
}
}

2 个答案:

答案 0 :(得分:0)

System.out.printf("%7s", primes); 

这会抛出异常primesArraylist%7s需要String

答案 1 :(得分:0)

public  static void printArray(ArrayList<Integer> primes){
    // You need to have a counter as you iterate over the list
    int count = 1;
    // Integer is autoboxed into an int when interating over prime
    for(int prime : primes){
        // "%7d" instead of "%7s" as d is used for integer but s is used for strings
        System.out.printf("%7d ", prime);
        // count++ will icrement count after this statement is called
        if (count++ % 10 == 0){
            System.out.println();
        }
    }
}