打印字符串数组的交替元素

时间:2017-12-26 15:36:59

标签: java arrays

You don't have permission to access /img/xprestashop-logo-1514296542.jpg.pagespeed.ic.AN7WOFIVVf.webp on this server.

我想打印字符串数组的交替元素。例如,package com.javaprograms; import java.util.Arrays; public class PracticeJava { public static void main(String args[]) { String[] array = {"ABC","XYZ","PQR","STW"}; //int num = array.length; for(int i=0;i<=array.length-1;i++) { System.out.println(Arrays.asList(array)); } } } {"ABC", "PQR"}。上面的代码不起作用。

2 个答案:

答案 0 :(得分:1)

为什么不循环进入整个数组并获取奇数或偶数元素然后打印出来? e.g。

for (int i = 0; i <= array.length - 1; i++) {
   if (i % 2 == 0) // all even or "if (i % 2 != 0)" all odd
      System.out.println(array[i]);
}

答案 1 :(得分:1)

在每个循环中增加2个循环变量:

打印所有偶数元素:

for (int i = 0; i < array.length; i = i + 2) {
    System.out.println(array[i]);
}
// Will print "ABC", "PQR"

打印所有奇数元素:

for (int i = 1; i < array.length; i = i + 2) {
    System.out.println(array[i]);
}
// Will print "XYZ", "STW"