1. 数组在创建之初就要确定元素个数,基于这个,表示数组在未初始化元素时,元素就有了默认值,且能对某一个元素进行操作
import java.util.Arrays;
public class ArrayTest03 {
public static void main(String[] args) {
int[] ints = new int[5];
String[] strings = new String[3];
boolean[] booleans = new boolean[3];
char[] chars = new char[5];
byte[] bytes = new byte[6];
A1[] a1s = new A1[6];
System.out.println("ints = " + Arrays.toString(ints));
System.out.println("strings = " + Arrays.toString(strings));
System.out.println("booleans = " + Arrays.toString(booleans));
System.out.println("chars = " + Arrays.toString(chars));
System.out.println("bytes = " + Arrays.toString(bytes));
System.out.println("a1s = " + Arrays.toString(a1s));
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
ints[3] = 2;
strings[2] = "hei";
booleans[1] = true;
chars[0] = 'a';
chars[1] = 35;
bytes[1] = 1;
a1s[1] = new A1();
System.out.println("ints = " + Arrays.toString(ints));
System.out.println("strings = " + Arrays.toString(strings));
System.out.println("booleans = " + Arrays.toString(booleans));
System.out.println("chars = " + Arrays.toString(chars));
System.out.println("bytes = " + Arrays.toString(bytes));
System.out.println("a1s = " + Arrays.toString(a1s));
}
}
class A1{}
输出:
ints = [0, 0, 0, 0, 0]
strings = [null, null, null]
booleans = [false, false, false]
chars = [, , , , ]
bytes = [0, 0, 0, 0, 0, 0]
a1s = [null, null, null, null, null, null]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ints = [0, 0, 0, 2, 0]
strings = [null, null, hei]
booleans = [false, true, false]
chars = [a, #, , , ]
bytes = [0, 1, 0, 0, 0, 0]
a1s = [null, OOPTest.A1@29453f44, null, null, null, null]
2. 初始化数组间接方式
例如:int[] ints = {1,2,3,4}
但是错误的是:
int[] ints;
ints = {1,2,3,5};
3. 利用数组简化编码:
对于某些任务来说,使用数组可以极大简化编码。例如,建设你想通过给定的数字的月份来获得一个该月份的英文名字。如果月份名称保存在一个数组中,给定月份的月份名可以简单通过下标获得。例如:
public class ArrayTest03 {
public static void main(String[] args) {
String[] moths = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
"November", "December"};
Scanner input = new Scanner(System.in);
System.out.println("请输入一个月份数字(1-12):");
int monthNumber = input.nextInt();
System.out.println("这个月是:" + moths[monthNumber-1]);
}
}
这样就避免了使用一大片的if。。。else的判断
4. 一副牌
编写一个程序,从一副牌中随机选出4张牌。
一副牌是52张,分位4中花色和13个不同的大小,按花色区分可把牌分位4组,按大小分可把牌分位13组。
所有的牌存于一个数组中,这个数组用从0到51的初始值来填充。
牌号从0到12、13到25、26到38以及39到51分别表示13张黑桃、13张红桃、13张方块、13张梅花,cardNumber/13决定牌的花色,cardNumber%13决定是具体花色中的哪张牌
5. 统计每个字母出现的次数
编写一个程序,用于统计一个字符数组中出现的每个字母出现的次数
本程序要点:chars存储的就是所有的随机字母字符,counts是每个字母在chars中出现的次数,如果字母(chars[i])是'a',那么它对应的计数器就是counts['a'-'a'] (即counts[0])。如果字母是'b', 因为'b'的Unicode码比'a'的统一码大1,所以它对应的计数器为counts['b'-'a'](即counts[1])。。。以此类推