day05-数组的操作_数组遍历-数组反转方式一
This commit is contained in:
28
day05/src/com/inmind/array01/Test06.java
Normal file
28
day05/src/com/inmind/array01/Test06.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package com.inmind.array01;
|
||||
/*
|
||||
获取数组中的最大值
|
||||
1.定义变量,保存数组0索引上的元素
|
||||
2.遍历数组,获取出数组中的每个元素
|
||||
3.将遍历到的元素和保存数组0索引上值的变量进行比较
|
||||
4.如果数组元素的值大于了变量的值,变量记录住新的值
|
||||
5.数组循环遍历结束,变量保存的就是数组中的最大值
|
||||
*/
|
||||
public class Test06 {
|
||||
//请定义一个长度为5的,初始化时固定赋值的整数数组,使用遍历,获取出数组中最大的值
|
||||
public static void main(String[] args) {
|
||||
int[] arr = {-1,-2,3,6,7};
|
||||
//1.定义变量,保存数组0索引上的元素
|
||||
int max = arr[0];
|
||||
//2.遍历数组,获取出数组中的每个元素
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
//3.将遍历到的元素和保存数组0索引上值的变量进行比较
|
||||
int temp = arr[i];//遍历到的每个元素
|
||||
//4.如果数组元素的值大于了变量的值,变量记录住新的值
|
||||
if (temp > max) {
|
||||
max = temp;
|
||||
}
|
||||
}
|
||||
//5.数组循环遍历结束,变量保存的就是数组中的最大值
|
||||
System.out.println("数组中最大的值:"+max);
|
||||
}
|
||||
}
|
||||
26
day05/src/com/inmind/array01/Test07.java
Normal file
26
day05/src/com/inmind/array01/Test07.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.inmind.array01;
|
||||
//数组的反转: 数组中的元素颠倒顺序,例如原始数组为1,2,3,4,5,反转后的数组为5,4,3,2,1
|
||||
public class Test07 {
|
||||
public static void main(String[] args) {
|
||||
//定义一个整数数组
|
||||
int[] arr = {1, 2, 3, 4, 5};
|
||||
//方式一:浪费空间,简单一点,创建新数组,进行反向遍历赋值
|
||||
int[] newArr = new int[arr.length];
|
||||
|
||||
/*
|
||||
arr1[0] = arr[arr.length - 1];
|
||||
arr1[1] = arr[arr.length - 1-1];
|
||||
arr1[2] = arr[arr.length - 1-2];
|
||||
arr1[3] = arr[arr.length - 1-3];
|
||||
*/
|
||||
for (int i = arr.length - 1; i >= 0; i--) {
|
||||
newArr[arr.length - 1 - i] = arr[i];
|
||||
}
|
||||
//对新数组正向遍历查看即可
|
||||
for (int i = 0; i < newArr.length; i++) {
|
||||
System.out.println(newArr[i]);
|
||||
}
|
||||
|
||||
}
|
||||
//方式二:不浪费空间,复杂一点,不创建新数组,在原数组的基础上进行反转
|
||||
}
|
||||
Reference in New Issue
Block a user