您的位置:首页 >Java二维数组的赋值和输出
发布于2023-04-30 阅读(0)
扫一扫,手机访问
public class Demo1 {
public static void main(String[] args) {
//声明一个二维数组:有三行,列数待定,数组结构表示为{{ },{ },{ }}
String s[][]=new String[3][];//动态赋值二维数组
s[0]=new String[3];
s[1]=new String[2];
s[2]=new String[3];
s[0][0]="a";
s[0][1]="b";
s[0][2]="c";
s[1][0]="d";
s[1][1]="e";
s[2][0]="f";
s[2][1]="g";
s[2][2]="h";
//String s[][]={{"a,b,c"},{"d,e"},{"f,g,h"}};静态赋值二维数组
for(int i=0;i<s.length;i++) {//s.length表示行数
System.out.print("{");
for(int j=0;j<s[i].length;j++) {//s[i].length表示列数
System.out.print(s[i][j]+" ");
}
System.out.print("}");
System.out.println();
}
}
}Java 随机给二维数组赋值,打印输出每个元素
代码:
import java.util.Random;
public class TestArrays1{
public static void main(String[] args){
//随机给二维数组赋值,打印输出每个元素
Random random=new Random();
int rand=0;//存储随机数
int[][] arrays=new int[3][4];//声明二维数组
//给数组赋值
for(int i=0;i<arrays.length;i++){
for(int j=0;j<arrays[i].length;j++){
rand=random.nextInt(100);//在0-100内随机生成一个正整数
arrays[i][j]=rand;
}
}
//打印输出(采用for循环)
System.out.println("采用for循环: ");
for(int i=0;i<arrays.length;i++){
for(int j=0;j<arrays[i].length;j++){
System.out.print(arrays[i][j]+" ");
}
}
//打印输出(采用增强for循环)
System.out.println();//换行
System.out.println("采用for循环: ");
for(int[] a:arrays){
for(int b:a){
System.out.print(b+" ");
}
}
}
}结果:

售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9