package src.test;
/*
* 数组是一种用于存储多个相同类型的存储模型
*
* 推荐格式
* 数据类型【】数组名;
*
*要求:求一组数里最大值
* */
public class 数组 {
public static void main(String[] args) {
int[] arr={12,45,98,74};
int max=arr[0];
for(int x=1;x<arr.length;x++){
if(arr[x]>max){
max=arr[x];
}
}
System.out.println("max:"+max);
}
}
package src.test;
/*
* 需求:{68, 23, 45, 67, 89, 998, 78, 56}有这样的数组,
* 要求:求和的元素个位和十位都不是7,并且只能是偶数。
*
* */
public class 数组元素求和 {
public static void main(String[] args) {
//定义一个静态数组
int[] arr = {68, 23, 45, 67, 89, 998, 78, 56};
//定义一个求和变量,初始值为0
int sum = 0;
//遍历数组
for (int x = 0; x < arr.length; x++) {
//判断累加
if (arr[x] % 10 != 7 && arr[x] / 10 % 10 != 7 && arr[x] % 2 == 0) {
sum += arr[x];
}
}
//输出求和变量值
System.out.println("sum:" + sum);
}
}
package src.test;
/*
* 需求:设计一个方法,用于比较两个数组的内容是否相同
* */
public class 数组内容相同 {
public static void main(String[] args) {
//定义两个数组,分别使用静态初始化完成数组元素的初始化
int[] arr = {11, 22, 33, 44, 55};
int[] arr2 = {11, 22, 33, 44, 55};
//调用方法,用变量接收
boolean flag = compare(arr, arr2);
//输出结果
System.out.println(flag);
}
//定义一个方法,用于比较两个数组的内容是否相同
/*
* 两个明确:
* 1.返回值类型:boolean
* 2.参数:int[] arr,int[] arr2
* */
public static boolean compare(int[] arr, int[] arr2) {
//首先比较数组的长度
if (arr.length != arr2.length) {
return false;
}
//遍历每一个元素
for (int x = 0; x < arr.length; x++) {
if (arr[x] != arr2[x]) {
return false;
}
}
//最后循环遍历结束后,返回true
return true;
}
}
package src.test;
//需求:设计一个方法用于获取数组中元素的最大值,调用方法并输出结果
public class 数组最大值 {
public static void main(String[] args) {
int[] arr = {12, 24, 34, 45};
// 调用获取最大值方法,要变量接收后返回结果
int number = getMax(arr);
//输出
System.out.println("number" + number);
}
//定义一个方法,用来获取数组最大值
/*
* 两个明确:
* 返回值类型
* 参数*/
public static int getMax(int[] arr) {
int max = arr[0];
for (int x = 1; x < arr.length; x++) {
if (arr[x] > max) {
max = arr[x];
}
}
return max;
}
}
package src.test;
public class 数组遍历 {
public static void main(String[] args) {
//需求:设计一个方法用于数组遍历,
// 要求遍历的结果是在一行上的。例如:[11,22,33,44,55]
//定义一个数组,用静态初始化完成数组元素初始化
int[] arr = {11, 22, 33, 44, 55};
//调用方法
printArray(arr);
}
//定义一个方法,用属猪遍历通用格式对数组进行遍历
/*
* 两个明确:
* 返回值类型 void
* 参数 int[] arr
* */
/*
public static void printArray(int[] arr) {
for (int x = 0; x < arr.length; x++) {
System.out.println(arr[x]);
}
}
*/
public static void printArray(int[] arr) {
System.out.print("[");
for (int x = 0; x < arr.length; x++) {
if (x == arr.length - 1) {
System.out.print(arr[x]);
} else {
System.out.print(arr[x] + ", ");
}
}
System.out.println("]");
}
}