写一段程序来阐述数组简单的应用
package com.liaojianya.chapter1;
import java.util.Random;
/**
* This program demonstrates the use of array.
* @author LIAO JIANYA
* 2016年7月20日
*/
public class ArrayAssignment8_3
{
public static void main(String[] args)
{
Random rand = new Random();
int[] a = null;
int[] b = null;
a = new int[rand.nextInt(10) + 1];
b = a;
System.out.println("the length of array_a : " + a.length);
System.out.println("the length of array_b : " + b.length + "\n");
for(int i = 0; i < a.length; i++)
{
a[i] = rand.nextInt(100);
System.out.print("a[" + i + "] = " + a[i] + "\t");
System.out.println("b[" + i + "] = " + b[i]);
}
if(a.length == 1)
{
System.out.println("The array_a only has one element.\n"
+ "So the max value of array_a is same as the min value!");
}
else
{
int max = a[0];
int min = a[0];
for(int i = 0; i < a.length; i++)
{
if(a[i] > max)
{
max = a[i];
}
else if(a[i] < min)
{
min = a[i];
}
}
System.out.println("\nThe max value of array_a is : " + max);
System.out.println("The min value of array_a is : " + min);
}
}
}
运行结果1:
the length of array_a : 1
the length of array_b : 1
a[0] = 70 b[0] = 70
The array_a only has one element.
So the max value of array_a is same as the min value!
运行结果2:
the length of array_a : 7
the length of array_b : 7
a[0] = 39 b[0] = 39
a[1] = 90 b[1] = 90
a[2] = 49 b[2] = 49
a[3] = 35 b[3] = 35
a[4] = 33 b[4] = 33
a[5] = 12 b[5] = 12
a[6] = 75 b[6] = 75
The max value of array_a is : 90
The min value of array_a is : 12
分析:
1)代码行:b = a;表示将a数组的引用赋值给数组b,这时a和b是指向同一个数组对象。即“一个数组,两个名字”
2)创建一个Random类型的对象rand,此对象可以灵活的产生随机数,代码行a = new int[rand.nextInt(10)+1]; 在rand.nextInt()后加1,可以避免出现0个元素数组。
若不加1,若随机到0,则会显示:
the length of array_a : 0
Exception in thread "main" the length of array_b : 0
java.lang.ArrayIndexOutOfBoundsException: 0
at com.liaojianya.chapter1.ArrayAssignment8_3.main(ArrayAssignment8_3.java:30)
3)将变量min与max初值设为数组的第一个元素后,再逐一的与数组中的各元素相比,比min小的就将该元素值赋给min存放,使得min中的值始终保持最小;同理,当该元素大于max时,就将该元素赋给max存放,使得max的值保持最大。
编写多维数组使用方法的程序如下:
package com.liaojianya.chapter1;
/**
* This program demonstrates the use of multiple array.
* @author LIAO JIANYA
* 2016年7月20日
*/
public class ThreeDimensionArray
{
public static void main(String[] args)
{
int sum = 0;
int[][][] a =
{
{{5, 1}, {6, 7}},
{{9, 4}, {8, 3}}
};
for(int i = 0; i < a.length; i++)
{
for(int j = 0; j < a[i].length; j++)
{
for(int k = 0; k < a[j].length; k++)
{
System.out.print("a[" + i + "][" + j + "][" + k + "] = " + a[i][j][k] + "\n");
sum += a[i][j][k];
}
}
}
System.out.println("sum = " + sum);
}
}
运行结果:
a[0][0][0] = 5
a[0][0][1] = 1
a[0][1][0] = 6
a[0][1][1] = 7
a[1][0][0] = 9
a[1][0][1] = 4
a[1][1][0] = 8
a[1][1][1] = 3
sum = 43