JAVA基础语法—数组
2-5 数组
概念
数组是相同数据类型的多个数据的容器。(其中的元素按 线性顺序 排列。)
格式
public static void main(String[] args) {
// 格式1.创建数组,指定数组中的内容。
// 数据类型[] 数组名称 = {数据1,数据2,数据3...数据n};
int[] ages = {10,11,12,13,14};
// 格式2.创建数组, 并指定长度, 不指定数组中的内容。
// 数据类型[] 数组名称 = new 数据类型[数组长度];
// 数组长度通过int数据指定
int[] ages2 = new int[10];
// 格式3.创建数组 , 不初始化
// 数据类型[] 数组名;
int[] nums;
// 格式4.创建数组, 并指定数组中的内容
// 数据类型[] 数组名称 = new 数据类型[]{内容1,内容2,内容3...内容n};
int[] ages = new int[] {11,12,13,14};
}
下标
// 通过下标操作数组数据的方式:
// 1. 给数组某个下标 赋值: 数组名称[下标] = 值;
ages[0] = 100;
System.out.println(ages[0]);
// 2. 从数组某个下标 取值: 数组名称[下标]
ages2[0] = 99;
System.out.println(ages2[0]);
数组长度
// 如何获取数组的长度: 数组名称.length
// 数组的遍历
for(int index=0; index<ages.length; index++) {
//index: 0 1 2 3 4
System.out.println(ages[index]);
}
常见问题
public static void main(String[] args) {
// 1.数组下标越界问题:
int[] nums = {10,11,12,13,14};
System.out.println(nums[5]);
// 2.空指针问题
int[] nums = null;
System.out.println(nums[1]);
}
寻找最大值/最小值
public static void main(String[] args) {
int[] nums = {10,30,40,33,22,20,11,0};
// 1.创建一个变量, 用于存储遍历数组时发现的最大值
int n = nums[0];
// 2.循环取出数组中的每一个内容, 从1开始
for(int i=1;i<nums.length;i++) {
// 将数组中的每一个内容与n比较, 如果比n大, 则将n的值赋值为这个内容。
n = n>nums[i]?n:nums[i];
}
System.out.println(n);
}
冒泡排序
原理:持续 比较相邻的元素。如果第一个比第二个大,就交换他们两个
public static void main(String[] args) {
int[] nums = {20,15,18,13,30,60};
int temp;
// 外层循环控制的是, 比较的轮数。
// 外层循环次数: length-1
for(int i=0;i<nums.length-1;i++) {
// 内层循环控制的是,每轮比较的次数
// 第i轮(i从0开始计算), 比较次数为:length-i-1
for(int j=0;j<nums.length-i-1;j++) {
if(nums[j]>nums[j+1]) {
//两两相比, 满足移动条件
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
// 排序已经完成。 下面是遍历打印查看的过程
for(int i=0;i<nums.length;i++) {
System.out.println(nums[i]);
}
}
二分查找
概述:二分查找要求数组数据必须采用顺 序存储结构有序排列。
public static void main(String[] args) {
int[] nums = {10,20,30,40,50,60,70,80,90};
//要查找的数据
int num = 20;
//关键的三个变量:
//1. 最小范围下标
int minIndex = 0;
//2. 最大范围下标
int maxIndex = nums.length-1;
//3. 中间数据下标
int centerIndex = (minIndex+maxIndex)/2;
while(true) {
System.out.println("循环了一次");
if(nums[centerIndex]>num) {
//中间数据较大
maxIndex = centerIndex-1;
}else if(nums[centerIndex]<num) {
//中间数据较小
minIndex = centerIndex+1;
}else {
//找到了数据 数据位置:centerIndex
break;
}
if(minIndex > maxIndex) {
centerIndex = -1;
break;
}
//当边界发生变化, 需要更新中间下标
centerIndex = (minIndex+maxIndex)/2;
}
System.out.println("位置:"+centerIndex);
}
多维数组
// 二维数组 格式:
// int[][] 二维数组名称 = new int[长度][]
public static void main(String[] args){
int[][] nums = new int[10][];
nums[0] = new int[]{1,2,3};
System.out.println(nums[0][2]);
}

浙公网安备 33010602011771号