1.数组的定义:
package com.list;
public class ListDemo {
public static void main(String[] args) {
int[] scores= {88,98,76,87};
//等同于以下步骤:
/*
* int[] scores;//定义scores数组;
* scores=new int[4];//定义数组长度;
* scores[0]=88;
* scores[1]=98;
* scores[2]=76;
* scores[3]=87;//赋值
*
*/
for(int i=0;i<scores.length;i++)
{
System.out.println("第"+(i+1)+"个元素是"+scores[i]);
}
}
}
输出结果为:
疑问:
这里的i为什么是从0开始执行循环的?
2.数组的访问:
package com.listcaculate;
public class ListCaculateDemo {
public static void main(String[] args) {
int[] nums= new int[]{ 61, 23, 4, 74, 13, 148, 20};
double sum=0;
int max=nums[0];
int min=nums[0];
for(int i=0; i<nums.length;i++)
{
if(max<nums[i]) {
max=nums[i];
}
if(min>nums[i]) {
min=nums[i];
}
sum=sum+nums[i];
}
double avg=sum/(nums.length);
System.out.println("最大值是:"+max);
System.out.println("最小值是:"+min);
System.out.println("平均值是:"+avg);
}
}
输出:
3.使用arrays类操作数组:
package com.arraylistdemo;
import java.util.Arrays;//导入arrays类
public class ArrayListDemo {
public static void main(String[] args) {
int[] nums=new int[] {9,27,8,0,6};
Arrays.sort(nums);
for(int i=0;i<nums.length;i++) {
System.out.println(nums[i]);//排序后依次输出
}
System.out.println(Arrays.toString(nums));//输出字符串数组
}
}
4.二维数组:
public class doublelist {
public static void main(String[] args) {
// 定义两行三列的二维数组并赋值
String[][] names={{"tom","jack","mike"},{"zhangsan","lisi","wangwu"}};
// 通过二重循环输出二维数组中元素的值
for (int i = 0; i <names.length; i++) {
for (int j = 0; j < names[i].length; j++) {
System.out.println(names[i][j]);
}
System.out.println();
}
}
}
输出为: