将一个数组拆分为两组,一个为奇数数组,一个为偶数数组。比如数组array12 3 1 5 10 8,拆分后奇数数组array j:3,1,5,偶数数组array o:12,10,8
import java.util.ArrayList;
import java.util.Arrays;
public class Test1 {
public static void main(String[] args) {
int[] array = new int[]{12, 3, 1, 5, 10, 8};
ArrayList<Integer> oddList = new ArrayList<>();
ArrayList<Integer> evenList = new ArrayList<>();
for (int i : array) {
if (i % 2 == 0) {
evenList.add(i);
} else {
oddList.add(i);
}
}
Integer[] oddArr = oddList.toArray(new Integer[]{});
Integer[] evenArr = evenList.toArray(new Integer[]{});
System.out.println("奇数数组:" + Arrays.asList(oddArr));
System.out.println("偶数数组:" + Arrays.asList(evenArr));
}
}
1 声明两个数值,arr1, arr2
2 循环数组arr
3 判断取余2 == 0的为偶数,添加到arr1中 其余的添加到arr2中
9.1.1 遍历数组通用格式:
int[] arr = {...}
for(int x=0;x<arr.length;x++){
arr[x] //对arr[x]进行操作
}
获取数组元素数量方法:
9.1.2 遍历数组基本用法:
代码块:
package cn.tedu.util;
// 遍历数组基本用法
public class day04 {
public static void main(String[] args) {
// 定义数组
int[] arr = {11,22,33,44,55};
// 使用通用的遍历格式
for(int x = 0;x<arr.length;x++){
System.out.print(arr[x]);
}
}
}
输出结果:
1122334455
9.1.3 遍历数组练习:
代码块:
package cn.tedu.util;
import java.util.Random;
// 遍历数组练习
public class day05 {
public static void main(String[] args) {
method();
method2();
method3();
method4();
method5();
}
// 5.统计数组里的偶数的和
public static void method5(){
int[] e = {53,65,34,92,11,46,53,82,66,16,55,39,27};
int sum = 0;
for(int x=0;x<e.length;x++){
if(e[x] % 2 == 0){
sum = sum + e[x];
}
}
System.out.println("数组里偶数的和是:" + sum);
}
// 4.存入10个随机的整数
public static void method4(){
int[] d = new int[10];
for (int x=0;x<d.length;x++){
d[x] = new Random().nextInt(100);
}
for(int i=0;i<d.length;i++){
System.out.print(d[i] + ",");
}
System.out.println(" ");
System.out.println("---------------------");
}
// 3.存入1到10
public static void method3(){
int[] c = new int[10];
for(int x=0;x<c.length;x++){
c[x] = x+1;
System.out.println(c[x]);
}
System.out.println("---------------------");
}
// 2.输出每个月的天数
public static void method2(){
int[] b = new int[]{31,29,31,30,31,30,31,31,30,31,30,31};
for(int x=0;x<b.length;x++){
System.out.println(x+1+"月有 " + b[x] + " 天");
}
System.out.println("---------------------");
}
// 1.遍历数组入门
public static void method(){
int[] a = new int[5];
System.out.println(a); // [I@4554617c是地址值
for(int x=0;x<a.length;x++){
System.out.println(a[x]);
}
System.out.println("---------------------");
}
}
输出结果:
[I@4554617c
0
0
0
0
0
---------------------
1月有 31 天
2月有 29 天
3月有 31 天
4月有 30 天
5月有 31 天
6月有 30 天
7月有 31 天
8月有 31 天
9月有 30 天
10月有 31 天
11月有 30 天
12月有 31 天
---------------------
1
2
3
4
5
6
7
8
9
10
---------------------
20,24,30,66,74,34,17,50,60,26,
---------------------
数组里偶数的和是:336