一、数组定义
定义:数组是一个固定长度的,包含了相同类型数据的?容器
? ?
二、声明数组
int[] a; 声明了一个数组变量。
[]表示该变量是一个数组
int 表示数组里的每一个元素都是一个整数
a 是变量名
但是,仅仅是这一句声明,不会创建数组
? ?
有时候也会写成int a[]; 声明的过程这种写法没有什么区别,不过考虑规范和性能,有一些区别,建议采用第一种写法。(记得以前看过的《疯狂Java讲义》和菜鸟教程的Java部分里有提到,两种写法会造成一些规范或者性能上的区别的)
? ?
public class HelloWorld { ????public static void main(String[] args) { ????????// 声明一个数组 ????????int[] a; ????} } |
? ?
三、创建数组
创建数组的时候,要指明数组的长度。?
new int[5]?
引用概念:?
如果变量代表一个数组,比如a,我们把a叫做引用?
与基本类型不同?
int c = 5; 这叫给c赋值为5?
声明一个引用 int[] a;?
a = new int[5];?
让a这个引用,指向数组
? ?
public class HelloWorld { ????public static void main(String[] args) { ????????//声明一个引用 ????????int[] a; ????????//创建一个长度是5的数组,并且使用引用a指向该数组 ????????a = new int[5];???????? ????????int[] b = new int[5]; //声明的同时,指向一个数组 ????} } |
? ?
四、访问数组
数组下标基0
下标0,代表数组里的第一个数
public class HelloWorld { ????public static void main(String[] args) { ????????int[] a; ????????a = new int[5]; ???????? ? ????????a[0]= 1;??//下标0,代表数组里的第一个数 ????????a[1]= 2; ????????a[2]= 3; ????????a[3]= 4; ????????a[4]= 5; ????} } |
? ?
五、数组长度
.length属性用于访问一个数组的长度
数组访问下标范围是0到长度-1
一旦超过这个范围,就会产生数组下标越界异常
? ?
public class HelloWorld { ????public static void main(String[] args) { ????????int[] a; ????????a = new int[5];???????? ????????System.out.println(a.length); //打印数组的长度???????? ????????a[4]=100; //下标4,实质上是"第5个",即最后一个 ????????a[5]=101; //下标5,实质上是"第6个",超出范围 ,产生数组下标越界异常???????? ????} } |
? ?
六、练习--数组最小值
题目:
首先创建一个长度是5的数组
然后给数组的每一位赋予随机整数
通过for循环,遍历数组,找出最小的一个值出来
? ?
0-100的 随机整数的获取办法有多种,下面是参考办法之一:
(int) (Math.random() * 100) |
注:上面一行代码中,Math.random() 会得到一个0-1之间的随机浮点数,然后乘以100,并强转为整型即可。
public class HelloWorld { ????public static void main(String[] args) { ????????int[] a = new int[5]; ????????a[0] = (int) (Math.random() * 100); ????????a[1] = (int) (Math.random() * 100); ????????a[2] = (int) (Math.random() * 100); ????????a[3] = (int) (Math.random() * 100); ????????a[4] = (int) (Math.random() * 100); ???????? ? ????????System.out.println("数组中的各个随机数是:"); ????????for (int i = 0; i < a.length; i++) ????????????System.out.println(a[i]);???????? ????????System.out.println("本练习的目的是,找出最小的一个值: "); ????} } |
? ?
官方答案:
? ?
public class HelloWorld { ????public static void main(String[] args) { ????????int[] a = new int[5]; ????????a[0] = (int) (Math.random() * 100); ????????a[1] = (int) (Math.random() * 100); ????????a[2] = (int) (Math.random() * 100); ????????a[3] = (int) (Math.random() * 100); ????????a[4] = (int) (Math.random() * 100); ?????????? ? ????????System.out.println("数组中的各个随机数是:"); ????????for (int i = 0; i < a.length; i++) ????????????System.out.print(a[i] + " "); ????????System.out.println(); ????????int min = 100; ????????for (int i = 0; i < a.length; i++) { ????????????if(??a[i] < min ) ????????????????min = a[i]; ????????} ????????System.out.println("找出来的最小数值是:" +min);???????? ????} } |
? ?
? ?
? ?
? ?
? ?
原文:https://www.cnblogs.com/xlfcjx/p/10773669.html