目录
一维数组
1.先声明,用new关键字进行内存分配
二维数组
1.先声明,用new关键字进行内存分配
练习题:
一维数组
1.先声明,用new关键字进行内存分配
例如:
数组元素类型 数组名字[];
数组元素类型[] 数组名字;
声明一维数组,代码如下:
int arr[]; //声明int型数组,数组中的每个元素都是int型数值
数值名字 = new 数值元素的类型[数组元素的个数];
数组下标从0开始
public class GrtDay{//创建类
public static void main(String[] args) {//创建主方法
int day[] = new int[]{5,7,1,2,4};//创建并初始化一维数组
for (int i=0;i<5;i++){//利用循环将信息输出
System.out.print(day[i]);
}
}
}
运行结果:
二维数组 1.先声明,用new关键字进行内存分配
例如:
数组元素类型 数组名字[][];
数组元素类型[][] 数组名字;
声明一维数组,代码如下:
int arr[][]; //声明int型数组,数组中的每个元素都是int型数值
public class Matrix{//创建类
public static void main(String[] args) {//创建主方法
int a[][] = new int[3][4];//定义二维数组
for (int i=0;i
运行结果:
练习题:
1.使用一维数组存储键盘字母 分别把键盘上每一排字母按键都保存成一个一维数组,利用数组长度分别输出键盘中3排字母键的个数。
public class Keys {
public static void main(String[] args) {
char[] firstRow = {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'};
char[] secondRow = {'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'};
char[] thirdRow = {'Z', 'X', 'C', 'V', 'B', 'N', 'M'};
System.out.println("键盘上第一排的字母键有" + firstRow.length + "个;");
System.out.println("键盘上第二排的字母键有" + secondRow.length + "个;");
System.out.println("键盘上第三排的字母键有" + thirdRow.length + "个。");
}
}
2.寻找空储物箱 超市有20个储物箱,现第2、3、5、8、12、13、16、19、20号尚未使用,使用数组的长度分别输出尚未使用的储物箱个数以及已经使用的储物箱个数。
public class StorageBox {
public static void main(String[] args) {
int[] totalNum = new int[20];
int[] emptyNum = {2, 3, 5, 8, 12, 13, 16, 19, 20};
System.out.println("超市中有储物箱" + totalNum.length + "个。");
System.out.println("超市中尚未被使用的储物箱有" + emptyNum.length + "个。");
System.out.println("超市中已经被使用的储物箱有" + (totalNum.length - emptyNum.length) + "个。");
}
}
3.模拟书柜放书 一个私人书柜有3层2列,分别向该书柜第1层第1列放入历史类读物,向该书柜第2层第1列放入经济类读物,向该书柜第2层第2列放入现代科学类读物。创建一个二维数组,并给该二维数组赋值。
public class BookCase {
public static void main(String[] args) {
String[][] bookshelf = new String[3][2];
bookshelf[0][0] = "历史类读物";
bookshelf[1][0] = "经济类读物";
bookshelf[1][1] = "科学类读物";
System.out.println("向该书柜第1层第1列放入" + bookshelf[0][0]);
System.out.println("向该书柜第2层第1列放入" + bookshelf[1][0]);
System.out.println("向该书柜第2层第2列放入" + bookshelf[1][1]);
}
}
4.输出古诗 创建Poetry类,声明一个字符型二维数组,将古诗《春晓》的内容赋值于二维数组,然后分别用横版和竖版两种方式输出。
public class Poetry {
public static void main(String[] args) {
char arr[][] = new char[4][]; // 创建一个4行的二维数组
arr[0] = new char[] { '春', '眠', '不', '觉', '晓' }; // 为每一行赋值
arr[1] = new char[] { '处', '处', '闻', '啼', '鸟' };
arr[2] = new char[] { '夜', '来', '风', '语', '声' };
arr[3] = new char[] { '花', '落', '知', '多', '少' };
System.out.println("-----横版-----");
for (int i = 0; i < 4; i++) { // 循环4行
for (int j = 0; j < 5; j++) { // 循环5列
System.out.print(arr[i][j]); // 输出数组中的元素
}
if (i % 2 == 0) {
System.out.println(","); // 如果是一、三句,输出逗号
} else {
System.out.println("。"); // 如果是二、四句,输出句号
}
}
System.out.println("n-----竖版-----");
for (int j = 0; j < 5; j++) { // 列变行
for (int i = 3; i >= 0; i--) { // 行变列,反序输出
System.out.print(arr[i][j]); // 输出数组中的元素
}
System.out.println(); // 换行
}
System.out.println("。,。,"); // 输出最后的标点
}
}



