Java—Day5课堂练习
package com.lovo.classes;
import java.util.Scanner;
public class day5Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入要查找的数组中心元素的长度:");
int N = sc.nextInt();
int[] num = new int[N];
int[] num1 = new int[N+1];
System.out.println("请输入二个数组:");
for (int i=0;i<N;i++){
System.out.print("请输入num["+i+"]"+"元素");
num[i] = sc.nextInt();
}
for (int i=0;i<N+1;i++){
System.out.print("请输入num1["+i+"]"+"元素");
num1[i] = sc.nextInt();
}
int longth = num.length;
int longth2 = num1.length;
int middle = longth/2;
int middle2 = longth2/2;
System.out.println("奇数个数数组的中心元素为:"+num[middle]);
System.out.println("偶数个数数组的中心元素为:"+num[middle2-1]+" "+num[middle2]);
int sum = 0;
for (int i=0;i<longth;i++)
sum += num[i];
System.out.println("该数组元素之和为:"+sum);
int[] array = {1,3,5,6,9};
int L = array.length;
if (L%2 == 0)
System.out.println("该偶数个数数组的中心元素为:"+
array[L/2-1]+"和"+array[L/2]);
else
System.out.println("该奇数个数数组的中心元素为:"+array[L/2]);
int[] arr = {1,2,3,4,5,6,7,8,9,10};
String str = "";
String str1 = "";
for (int i=0;i<arr.length;i++){
if (i%2!=0)
str = str + arr[i] + " ";
if (arr[i]%2!=0)
str1 = str1 + arr[i] + " ";
}
System.out.println("奇数下标元素:"+str);
System.out.println("奇数:"+str1);
int sum1 = 0;
for (int i=0;i<arr.length;i++){
System.out.print(arr[i]*2+" ");
sum1 += arr[i];
}
arr[0] = sum1;
System.out.println();
System.out.println("将所有元素之和添加到第一个元素中:"+arr[0]);
for (int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
int[] A = {1,2,3,4,5,6,7,8,9,10};
int M=0,N1=0;
for (int i=0;i<A.length;i++){//记录满足下标被二整除的个数
if (i%2!=0)
M++;
if (A[i]%2==0)//记录元素是偶数的个数
N1++;
}
int[] B = new int[10];
int[] C = new int[10];
String strB = "";
String strC = "";
for (int i=0;i<A.length;i++){
if (i%2!=0){
B[i] = A[i];
strB = strB + B[i] + " ";
}
if (A[i]%2==0){
C[i] = A[i];
strC = strC + C[i] + " ";
}
}
int index = 0;
int index1 = 0;
for (int i=0;i<A.length;i++)
{
if (i%2!=0)//奇数下标元素存到B【】数组里面
B[index++] = A[i];
if (A[i]%2==0)//偶数元素存到C【】数组里面
C[index1++] = A[i];
}
System.out.print("B数组为:");
for (int i=0;i<M;i++)
System.out.print(B[i]+" ");
System.out.println();
System.out.print("C数组为:");
for (int i=0;i<N;i++)
System.out.print(C[i]+" ");
System.out.println();
System.out.println("奇数位置元素为:"+strB+"\n"+"偶数元素为:"+strC);
}
}