1.如何遍历如下的二维数组
int arr = new int{{t1},{7,8},{3,4,5},{63,78,34,55}};
System.out.println(Arrays.deepToString(arr));
2.定义一个4行4列的二维数组,将对角线的值赋为1,其他为0
public class demo1 { public static void main(String[] args) { int [][] a = new int [4][4]; for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ if(i+j==3||i==j){ a[i][j]=1; }else{ a[i][j]=0; } if(j==4){ } System.out.print(a[i][j]+" "); }System.out.println(); } } }
3.获取arr数组中所有元素的和。 提示:使用for的嵌套循环即可。 提示:"-"符号表示为空
public class demo1 { public static void main(String[] args) { int [][] a = {{3,5,8},{12,9},{7,0,6,4}}; int sum=0; for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ sum=sum+a[i][j]; } }System.out.println(sum); } }
i\j | j=0 | j=1 | j=2 | j=3 |
---|---|---|---|---|
i=0 | 3 | 5 | 8 | - |
i=1 | 12 | 9 | - | - |
i=2 | 7 | 0 | 6 | 4 |
-
声明:
int []x; int [][]y; //请分析: //x,y变量赋值以后,以下选项允许通过编译的是: !a) x[0] = y; ! b) y[0] = x; c) y[0][0] = x; d) x[0][0] = y; e) y[0][0] = x[0]; f) x = y;
5.实际案例
在一个二维数组中存放了三名学生的语文和数学的成绩,从键盘输入三名学生的成绩存储到二维数组中,分别求语文和数学的总成绩及平均分并输出。
import java.util.Scanner; public class demo1 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("请先输入3位同学的语文成绩,输入完成后再输入数学成绩"); Double[][] a=new Double[2][3]; Double ywsum=0.0,sxsum=0.0; for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ Double c=sc.nextDouble(); a[i][j]=c; if (i==0){ ywsum=ywsum+a[i][j]; }else{ sxsum=sxsum+a[i][j]; } } }System.out.println("语文总成绩"+ywsum); System.out.println("语文平均分"+ywsum/3); System.out.println("数学总成绩"+sxsum); System.out.println("数学平均分"+sxsum/3); } }
1.需求:打印杨辉三角形(行数可以键盘录入)(建议先将规律找出来!)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
代码:
import java.util.Scanner;
public class demo1 {
public static void main(String[] args) {
System.out.println("输入行数");
Scanner sc=new Scanner(System.in);
int c=sc.nextInt();
int [][] a=new int[c][];
for(int i=0;i<a.length;i++){
a[i]=new int[i+1];
for(int j=0;j<a[i].length;j++){
if(j==0||i==j){
a[i][j]=1;
}else {
a[i][j]=a[i-1][j-1]+a[i-1][j];
}System.out.print(a[i][j]+" ");
}System.out.println();
}
}
}