AP计算机教程8-2:操作二维数组
声明二维数组
在声明二维数组时,先明确数组中会存放的元素类型,然后加上[][]
以表示是该类型的二维数组,之后再加上至少一个空格以及数组的名称。声明数组并不等同于创建数组。Java数组也是一种object,试图操作未创建的数组会打印出null
,意味着数组还未指向任何object。
为创建数组,先使用new
关键字后接空格,再加上类型以及方括号中的行索引和列索引,像这样new int[numRows][numCols]
。二维数组中的元素个数是行数乘以列数。
以下代码创建了名为ticketInfo
的二行三列二维数组以及名为seatingChart
的三行二列二维数组。
ticketInfo = new int [2][3]; seatingChart = new String [3][2];
为数组赋值
在数组创建时,所有数值类型被设为0
,对象引用被设为null
,布尔类型则为false
。为显式将值赋给数组,你需要先写数组名称后接[]
内的行索引和列索引,最后是=
和希望赋给的值。
public class Test { public static void main(String[] args) { // declare arrays int[][] ticketInfo; String[][] seatingChart; // create arrays ticketInfo = new int [2][3]; seatingChart = new String [3][2]; // initialize the array elements ticketInfo[0][0] = 15; ticketInfo[0][1] = 10; ticketInfo[0][2] = 15; ticketInfo[1][0] = 25; ticketInfo[1][1] = 20; ticketInfo[1][2] = 25; seatingChart[0][0] = "Jamal"; seatingChart[0][1] = "Maria"; seatingChart[1][0] = "Jacob"; seatingChart[1][1] = "Suzy"; seatingChart[2][0] = "Emma"; seatingChart[2][1] = "Luke"; // print the contents System.out.println(ticketInfo); System.out.println(seatingChart); } }
以上代码的输出符合你的预期么?事实上,如果直接使用println
输出数组,仅会得到数组object的引用。
0:00
Which of the following sets the value for the 3rd row and 2nd column of a 2D array called nums
?
你还可以在创建数组时对其进行初始化(赋值)。在这种情况下无需明确数组的大小——其会由所给定的初始值的数量决定。以下的代码创建了名为ticketInfo
的二行三列数组以及名为seatingInfo
的三行二列数组。
int[][] ticketInfo = {{25,20,25}, {25,20,25}}; String[][] seatingInfo = {{"Jamal", "Maria"}, {"Jake", "Suzy"}, {"Emma", "Luke"}};
读取数组元素
为获得二维数组中的某个具体元素,也同样是写数组名称后接[]
内的行索引和列索引,可以查看以下示例代码并试着运行它。
int[][] ticketInfo = {{25,20,25}, {25,20,25}}; String[][] seatingInfo = {{"Jamal", "Maria"}, {"Jake", "Suzy"}, {"Emma", "Luke"}}; int value = ticketInfo[1][0]; String name = seatingInfo[0][1];
What is the value of name
after the code above executes?
[0][1]
对应的是第一行第二列的元素。
0 条评论