声明数组
- int[] a;
or - int a[];
创建数组
- int[] a = new int[100];
创建数组时对象数组的元素初始化为null
获取元素个数
- array.length
for each 循环
- 格式
for(variable:collection) statement
定义一个变量用于暂存集合中的每一个元素,并执行相应的语句 - 例子
for(int element : a)
System.out.println(element);
数组排序
使用Arrays类中的sort方法
程序清单
import java.util.Arrays;
import java.util.Scanner;
public class LotteryDrawing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you need to draw?");
int k = in.nextInt();
System.out.print("What is the highest number you can draw?");
int n = in.nextInt();
//将1到n填充到数组当中
int[] number = new int[n];
for(int i= 0;i < number.length; i++){
number[i] = i+1;
}
//抽取K个数,并放入另一个数组
int[] result = new int[k];
for (int i = 0; i < result.length; i++){
//产生0到(n-1)的随机数
int r = (int)(Math.random() * n);
result[i] = number[r];
number[r] = number[n-1];
n--;
}
//输出排序后的数组
Arrays.sort(result);
System.out.println("Bet the following combination. It'll make you rich!");
for (int r : result)
System.out.println(r);
}
}