4.22学习内容

1.一维数组

package ArrayTest;

public class Demo {

	public static void main(String[] args) {
		int a1[];
		int[] a2[];
		int a3[] = new int[3];//数组的创建
		
		int a4[] = {1,2,3,4};
		int a5[] = new int[] {1,2,3,4,5};//数组的初始化
		
		System.out.println(a5.length);//返回数组的长度
		
		int a6[] = {31,28,31,30,31,30,31,31,30,31,30,31};
		for(int i = 0;i<a6.length;i++) {
			System.out.println("第"+(i+1)+"月有"+a6[i]+"天");
		}
	}
}

2.二维数组

package ArrayTest;

public class Dome2 {//春晓的横版与竖版

	public static void main(String[] args) {
		char a[][] = new char[5][6];
		a[1] = new char[]{'春','眠','不','觉','晓',','};
		a[2] = new char[]{'处','处','闻','啼','鸟','。'};
		a[3] = new char[]{'夜','来','风','雨','声',','};
		a[4] = new char[]{'花','落','知','多','少','。'};
		System.out.print("---横版---");
		for(int i = 0;i<a.length;i++) {
			for(int j = 0;j<a[i].length;j++) {
				System.out.print(a[i][j]);
			}
			System.out.println();
		}
		System.out.println("---竖排排列---");
		for(int j = 0;j<6;j++) {
			for(int i = 4;i>0;i--) {
				System.out.print(a[i][j]);
			}
			System.out.println();
		}
	}
}

在这里插入图片描述

3.数组的遍历

过于简单,不再赘述
for循环或者foreach循环

4.填充和批量替换数组元素


import java.util.Arrays;

public class Dome3 {

	public static void main(String[] args) {
		int a[] = new int[5];
		Arrays.fill(a, 5);
		for(int b :a) {
			System.out.println(b);
		}
		
		Arrays.fill(a,2,4,7);//替换2~3的数字为7
		for(int b :a) {
			System.out.println(b);
		}
	}
}

5.对数组进行排序以及复制



import java.util.Arrays;

public class Dome3 {

	public static void main(String[] args) {
		int a[] = new int[] {1,2,6,3,8,3};
		Arrays.sort(a);//数组升序排列
		for(int b:a) {
			System.out.print(b);
		}
		System.out.println();
		
		int b[] = Arrays.copyOf(a, 3);//如果大于原数组长度其余补0
		for(int c:b) {
			System.out.print(c);
		}
		System.out.println();
		
		int c[] = Arrays.copyOfRange(a, 2, 4);//复制指定位置
		for(int x:c) {
			System.out.print(x);
		}
	}
}

6.冒泡排序

package ArrayTest;

public class Demo {

	public static void main(String[] args) {
		int a[] = {1,9,3,6,2,5,4,7};
		for(int i = 1; i<a.length;i++) {
			for(int j = 0;j<a.length-i;j++) {
				if(a[j]>a[j+1]) {
					int b = a[j];
					a[j] = a[j+1];
					a[j+1] = b;
				}
			}
		}
		for(int c:a) {
			System.out.print(c);
		}
	}
}

7.选择排序

package ArrayTest;

public class Dome2 {

	public static void main(String[] args) {
		int []a = {1,6,3,9,0,2,5,4,3,10};
		int flag;
		for(int i = 1;i<a.length;i++) {
			flag = 0;
			for(int j = 1;j<=a.length-i;j++) {
				if(a[flag] < a[j]) {
					flag = j;
				}
			}
			int t = a[a.length-i];
			a[a.length-i] = a[flag];
			a[flag] = t;
		}
		
		for(int s:a) {
			System.out.print(s+",");
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值