一、数组
用来将同类的数组放到一起的方法。
1.定义数组的方式
// nums是一个引用 数组的下标一般从0开始
// int[] nums = {1,2,3};
int[] nums1 = new int[3];
System.out.println(nums[1]);
2.给数组赋值
// 数组一但在内存中分配了空间,就不能改变。不能超出创建数组时定义的数组长度。
int[] nums = new int[3];
nums[0] = 1;
nums[1] = 2;
nums[2] = 3;
nums[3] = 4;
// 定义和赋值在一起
int[] nums2 = {1,2,3,4,5,6,7};
System.out.println(nums2[2]);
3.二维数组
int a[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
4.循环遍历数组,打擂台:
// 打擂台找最大值
int[] nums = {1,19,20,3,7,9,22};
int max = 0;
for (int i = 0;i < nums.length;i++){
if (max <= nums[i]){
max = nums[i];
}
}
System.out.println(max);
5.查找特定的数字的下标
// 查找5的下标
int[] nums = {1,2,3,4,5,9};
int target = -1;
for (int i = 0;i < nums.length;i++){
if (nums[i] == 5){
target = i;
}
}
System.out.println(target);
6.交换同一个数组内的两个数值
// 交换nums数组内第一个数字和第三个数字的内容。
int[] nums = {1,2,3,4,5,9};
int temp = nums[0];
nums[0] = nums[2];
nums[2] = temp;