我正在尝试编写代码来显示偶数元素到偶数索引和奇数到奇数索引,如果添加的数字相同,则相应地添加零。
例子:
x = [1,2,3,4] 输出:2 1 4 3 x = [1 1 1 4] 输出:4 1 0 1 0 1
我达到了偶数和奇数位置,但在那之后就卡住了。
下面是我的代码。
import java.util.*;
class ArrayDemo3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Size of Array :: ");
int size = s.nextInt();
int[] x = new int[size];
System.out.println("Array Created having the size :: " + size);
System.out.println("Enter Elements for Array :: ");
for (int i = 0; i < size; i++) {
System.out.println("Enter element no-" + (i + 1) + " ::");
x[i] = s.nextInt();
}
System.out.println("Contents of Array ::");
for (int i = 0; i < size; i++) {
System.out.print(x[i] + " ");
}
for (int i = 0; i < size; i = i + 1) {
int even = 0;
int odd = 1;
if (i < size && x[i] % 2 == 0) {
System.out.print("even : ");
even = even + i;
System.out.print("position" + i + " " + x[i] + " ");
} else {
System.out.print("odd : ");
odd = odd + i;
System.out.print(i + " " + x[i] + " ");
}
if (even < size && odd < size) {
int temp = x[even];
x[even] = x[odd];
x[odd] = temp;
} else {
}
//System.out.print(x[i] + " ");
}
}
}
江户川乱折腾
收到一只叮咚
长风秋雁
相关分类