4:数组常见操作:
数组遍历(依次输出数组中的每一个元素)
class Demo {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6};
print(arr);
}public static void print(int[] arr){
for (int i = 0;i < arr.length ;i++ ) {
System.out.print(arr[i]);
}
}
}
数组获取最值(获取数组中的最大值最小值)
class Demo {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7};
int max =getMax(arr);
System.out.println(max);
}public static int getMax(int[] arr){
int max = arr[0];
for (int i = 1;i < arr.length ;i++ ){
if (arr[0]<arr[i]) {
max = arr[i];
}
}
return max;
}
}
数组元素逆序 (就是把元素对调)
class Demo {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7};
reverse(arr);
print(arr);
}public static void reverse(int[] arr){
for (int i = 0;i < arr.length/2 ;i++ ) {
int temp = arr[i];
arr[i] = arr[arr.length-1-i];
arr[arr.length-1-i] = temp;
}
}
public static void print(int[] arr){
for (int i = 0;i < arr.length ;i++ ) {
System.out.print(arr[i]);
}
}
}
数组查表法(根据键盘录入索引,查找对应星期)
import java.util.Scanner;
class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入");
int index = sc.nextInt();
char a = getIndex(index);
System.out.println("星期" + a);
}
public static char getIndex(int index){
char[] arr = {' ','一','二','三','四','五','六','日'};
return arr[index];
}
}
数组元素查找(查找指定元素第一次在数组中出现的索引)
import java.util.Scanner;
class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入");
int[] arr = {1,4,3,2,5,8,7,6};
int value = sc.nextInt();
int a = getIndex(arr,value);
System.out.println(a);
}
public static int getIndex(int[] arr,int value ){
for (int i = 0 ;i < arr.length ;i++ ) {
if (arr[i] == value) {
return i;
//System.out.println(i);
}
}return -1;
}
}
5:二维数组定义格式?
格式1:规则的矩形。
int[][] arr = new int[3][2];
变形为:
int[] arr[] = new int[3][2];
int arr[][] = new int[3][2];
格式2:不规则的矩形。
int[][] arr = new int[5][];
/*arr[0] = new int[2];
arr[1] = new int[2];
arr[2] = new int[2];*/
格式3:
int[] arr = {1,2,3,4,5};
int[][] arr = { {1,2,3},{4,5},{6,7,8}};
常见操作:
int[][] arr = { {1,2,3},{4,5},{6,7,8,9}};
看懂针对每种格式的内存图解?
6:案例
A:二维数组遍历
B:公司年销售额求和
某公司按照季度和月份统计的数据如下:单位(万元)
第一季度:22,66,44
第二季度:77,33,88
第三季度:25,45,65
第四季度:11,66,99
class Demo {
public static void main(String[] args) {
int[][] arr= {{22,66,44},{77,33,88},{25,45,65},{11,66,99}};
int sum = 0;
for (int i = 0;i < arr.length ;i++ ) {
for (int j = 0;j < arr[i].length;j++ ) {
sum += arr[i][j];
}
}
System.out.println(sum);
}
} |