5.二维数组以及数组练习挑战
1)定义二维数组
int[][] nums = {{2,4,6},{3,5},{7,8,9,10}};
String[][] names = new String[][]{{"tom","ben","ad"},{"ce","st"}};
String[][] names2 = new String[4][3];
2)访问和遍历
访问:
System.out.println(names[1][0]);
System.out.println(nums[2][3]);
遍历1:
for (int i = 0; i < names2.length; i++) {
String[] nameA = names2[i];
for (int j = 0; j < nameA.length; j++) {
nameA[j] = "a"+i+j;
System.out.println(names2[i][j]);
}
}
遍历2:
for (String[] strings : names2) {
for (String string : strings) {
System.out.println(string);
}
}
练习:
1.创建一个3*3的二维数组,包括9个字符串名字,查找并输出“tom”在几行几列,如果tom不在内,则输出他不在。
String[][] name = {{"tom","com","aom"},{"mary","micro","fan"},{"chan","dan","ken"}};
for (int i = 0; i < name.length; i++) {
String[] nameA = name[i];
for (int j = 0; j < nameA.length; j++) {
if (nameA[j]=="tom") {
System.out.println("tom在第"+(i+1)+"行,第"+(j+1)+"列");
}
}
}
System.out.println("他不在");
2.找到tom和micro,给他们交换位置。
String[][] name = {{"tom","com","aom"},{"mary","micro","fan"},{"chan","dan","ken"}};
int a = 0;
int b = 0;
int c = 0;
int d = 0;
String temp = new String();
String nameN = new String();
String nameM = new String();
for (int i = 0; i < name.length; i++) {
String[] nameA = name[i];
for (int j = 0; j < nameA.length; j++) {
if (nameA[j]=="micro") {
nameN = name[i][j];
a = i;
b = j;
System.out.println("交换前micro在第"+(i+1)+"行,第"+(j+1)+"列");
}
if (nameA[j]=="tom") {
nameM = name[i][j];
c = i;
d = j;
System.out.println("交换前tom第"+(i+1)+"行,第"+(j+1)+"列");
}
}
}
temp = name[a][b];
name[a][b] = name[c][d];
name[c][d] = temp;
for (int i = 0; i < name.length; i++) {
String[] nameA = name[i];
for (int j = 0; j < nameA.length; j++) {
if (nameA[j]=="micro") {
System.out.println("交换后micro在第"+(i+1)+"行,第"+(j+1)+"列");
}
if (nameA[j]=="tom") {
System.out.println("交换后tom第"+(i+1)+"行,第"+(j+1)+"列");
}
}
}
挑战:
1.初始化一个包括100个元素的数组。
2.每个元素是用1-10之间的随机数。
3.打印输出8一共出现了几次。
int nums[] = new int[100];
Random ran = new Random();
int a = 0;
for (int i : nums) {
nums[i] = ran.nextInt(10)+1;
System.out.println(nums[i]);
if (nums[i]==8) {
a++;
}
}
System.out.println("共打印"+a+"次数字8。");