数组遍历
// 遍历一维数组 arr 数组中的元素
class demo {
public static void main(String[] args) {
int[] arr = {1, 42, 23, 14, 53, 2, 7, 8};
for (int i = 0; i < arr.length; i++) { // arr.length 获取数组中所有元素的个数
System.out.println(arr[i]); // 依次输出所有元素
}
}
}
--------------------------
1
42
2
7
8
//遍历二维数组
/*
* 需求:键盘输入2 给数求和
*/
import java.util.Scanner;
// 遍历 arr 数组中的元素
class demo {
public static void main(String[] args) {
int[][] arr = { {4,2}, {2,3,4} ,{1,2}, {1,3,1}, {2,6}};
for (int i = 0; i < arr.length; i++) { // arr.length 获取数组中所有元素的一维数组
for(int j = 0; j < arr[i].length;j++){ // 获取一维数组中的所有元素
System.out.print(arr[i][j] + "\t");
}
System.out.println(" ");
}
}
}
-------------------------
4 2
2 3 4
1 2
1 3 1
2 6
数组求和
// 求 arr 数组中的元素和,
class demo {
public static void main(String[] args) {
int[][] arr = {{4, 2}, {2, 3, 4}, {1, 2}, {1, 3, 1}, {2, 6}};
// int [] arr = {1,2,3,4,7,5,6};
int result = 0; // 定义变量,记录结果
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
result += arr[i][j]; // 获取每个元素,并且相加
}
}
System.out.println(result);
}
}
----------------
31
数值取最值
// 求 arr 数组中的最大值
class demo {
public static void main(String[] args) {
int[][] arr = {{4, 2}, {2, 23, 4}, {1, 2}, {1, 13, 1}, {2, 6}};
// int [] arr = {1,2,3,4,7,5,6};
int max = arr[0][0]; // 设置一个初始值,一定是元素中的值
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (max < arr[i][j]) { // 依次拿元素中的值,进行比较,如果大,则赋值给初识的值
max = arr[i][j];
}
}
}
System.out.println(max);
}
}
=================
23
反转
// 数组元素反转
class demo {
public static void main(String[] args) {
//int[][] arr = {{4, 2}, {2, 23, 4}, {1, 2}, {1, 13, 1}, {2, 6}};
int[] arr = {1, 2, 3, 4, 5, 6};
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i]; //使用第三方变量交换2个变量之间的值
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]); // 依次打印出反转后的数组元素
}
}
}
---------------------------------
654321