2015-11-24 46 views
-1

设计一个函数,其职责是很好地显示素数数组。它应该显示每行数组10的内容。打印和println的组合将是必要的。在宽度为7的字段中显示每个 数字(使用printf)。从不同的方法打印ArrayList

这是我的,但我不确定是否正确。

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

我不认为这是正确的。我相信问题是要求你显示素数'ArrayList'中的元素。要做到这一点,你应该考虑使用'for'循环遍历所有元素。要显示每行10行,可能需要确定循环增量是否可以用'%'整除10。 –

+1

不确定是否正确?运行它,看它是否打印出应该打印的方向。 – csmckelvey

回答

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(); 
     } 
    } 
} 
0
System.out.printf("%7s", primes); 

这将抛出一个异常primesArraylist%7s需要String