1、
通过example1和2说明了什么?
数组可以是任意的数据类型
但同一数组不能出现多种数据类型
package test;
public class test1 {
public static void main(String[] args) {
example1();
example2();
}
public static void example1() {
int[] x = new int[50]; //定义数组的格式,初始值为0开始
System.out.println(x[0]);
System.out.println(x[1]);
System.out.println(x[40]);
}
public static void example2() {
double[] y = new double[50];
System.out.println(y[0]);
}
}
2、
package test;
public class test1 {
public static void main(String[] args) {
example3();
example4();
example5();
example6();
}
public static void example3() {
int[] a = new int[]{
1, 4, 6, 8, 12
};//数组的赋值,等同int[] a = {1,4,6,8,12};
System.out.println(a[0]);//输出1
System.out.println(a[1]);//输出4,容易误认为输出1
System.out.println(a[2]);//输出6
System.out.println(a.length);//输出5
// 注意,每个数组的索引都有一个范围,即0~length-1。
// 在访问数组的元素 时,索引不能超出这个范围,否则程序会报错。
}
public static void example4() {
int[] b = new int[5];
b[3] = 2;
System.out.println(b[3]);//输出2
b = null;
// System.out.println(b[2]);//提示空指针异常,说明变量指向的必须是有效的数组对象
}
public static void example5() {
int[] c = {3, 5, 7, 2, 9};
for (int i = 0; i < c.length; i++) {//用for循环来遍历数组
System.out.println("\t" + c[i]);//输出3,5,7,2,9
}
}
public static void example6() {
int[] d = {6, 3, 7, 5, 9, 2};
int max = d[0];
for (int i = 1; i < d.length; i++) {
if (d[i] > max) {
//找最大值。关键找中间值,然后利用数组循环,比较与中间值的大小
max = d[i];
}
System.out.println(max);//输出为9
}
}
}
3、
注意 int[][]可以看成几行几列,没有0的,并非与 int max = d[0] 这里中括号的意义相同。