数组(定义方式,赋值及使用数组)

一、数组

用来将同类的数组放到一起的方法。

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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值