Java 中的数组

时间:2021-05-12 03:06:24

1.声明数组
String [] arr;
int arr1[];
String[] array=new String[5];
int score[]=new int[3];

2.初始化数组;
//静态初始化
int arr2[]=new int[]{1,2,3,4,5};
String[] array1={"马超","马云","关羽","刘备","张飞"};
String[] array2=new String[]{"黄渤","张艺兴","孙红雷","小猪","牙哥","黄磊"};
int score[]=new int[3];
//动态初始化
for(int i=0;i<score.length;i++)
{
  score[i]=i+1;
}

3.查看数组长度;
int length=array1.length;
System.out.println("length: "+array1.length);

4.遍历数组;
for (int i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}

5.int数组转成string数组;
int[] array3={1,2,3,4,5,6,7,8,9,0};
String arrStrings=Arrays.toString(array3);
System.out.println(arrStrings);

6.一般数组:
实例常见数组类型:

String [] sichuan={"成都","绵阳","德阳"};
String [] yunnan={"丽江","大理","昆明"};

String [] zhejiang={"杭州","嘉兴","温州"};

String[][] citys ={sichuan,yunnan,zhejiang};

7.在数组中有的二维数组
用以上的例子:
输出省份下的 城市:
String [] shengfen={"1四川","2云南","3浙江"};
for(String b:shengfen){
System.out.println(b);
}
System.out.println("请输入1-3的数字选取你需要查找的");
Scanner input=new Scanner(System.in );
int a=input.nextInt();
String [] sichuan={"成都","绵阳","德阳"};
String [] yunnan={"丽江","大理","昆明"};
String [] zhejiang={"杭州","嘉兴","温州"};

String[][] citys ={sichuan,yunnan,zhejiang};


for (int i = 0; i < citys.length; i++) {

System.out.println(citys[a-1][i]);

以上都是些小知识,***