这是我的示例代码
Object[] a=new Object[n];
for(int i=4;i<a.length;i+=5)
{
System.out.println(a[i]);
}
for(int i=6;i<a.length;i+=7)
{
System.out.println(a[i]);
}
答案 0 :(得分:1)
尝试使用Modulus operator %
。无需循环两次。
public static void main(String[] args) throws ParseException {
//Object[] a = new Object[20];
Object[] a = new Object[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35 };
for (int i = 0; i < a.length; i++) {
if (i % 5 == 4 && i % 7 == 6) {
System.out.println("Multiple of 5 and 7 both - " + a[i]);
} else if (i % 5 == 4) {
System.out.println("Multiple of 5 - " + a[i]);
} else if (i % 7 == 6) {
System.out.println("Multiple of 7 - " + a[i]);
}
}
}
<强>输出强>
Multiple of 5 - 5
Multiple of 7 - 7
Multiple of 5 - 10
Multiple of 7 - 14
Multiple of 5 - 15
Multiple of 5 - 20
Multiple of 7 - 21
Multiple of 5 - 25
Multiple of 7 - 28
Multiple of 5 - 30
Multiple of 5 and 7 both - 35
答案 1 :(得分:0)
你可以改用计数器。
Object[] a = new Object[n];
int counter = 2;
int elementsCounter = 5;
for (int i = 0; i < a.Length; i++)
{
if (i == elementsCounter )
{
System.out.println(a[i]);
elementsCounter += counter;
counter++;
}
}