声明一个变量就是在内存空间划出一块合适的空间
声明一个数组就是在内存空间划出一串连续的空间
数组长度固定不变,避免数组越界
数组中的所有元素必须属于相同的数据类型
1,声明数组
2,分配空间:
score = new int[30];
avgAge = new int[6];
name = new String[30];
声明数组并分配空间:
数据类型[ ] 数组名 = new 数据类型[大小] ;
3,赋值
score[0] = 89;
score[1] = 79;
score[2] = 76;
……
int[ ] score = {89, 79, 76};
-------------------------------------------------------------------------------
Scanner input = new Scanner(System.in);
for(int i = 0; i < 30; i ++){
score[i] = input.nextInt();
}
-------------------------------------------------------------------------------
int [ ] score = {60, 80, 90, 70, 85};
int sum = 0;
double avg;
for(int i = 0; i < score.length; i++){
sum = sum + score[i];
}
avg = sum / score.length;
-------------------------------------------------------------------------------
if(i==array.length)
{
System.out.println("不包含");
}
-------------------------------------------------------------------------------
Arrays类的sort()方法: 对数组进行升序排列:
int[] scores = new int[5]; //成绩数组
Scanner input = new Scanner(System.in);
System.out.println("请输入5位学员的成绩:");
for(int i = 0; i < scores.length; i++)
{
scores[i] = input.nextInt();
}
Arrays.sort(scores);
System.out.print("学员成绩按升序排列:");
for(int i = 0; i < scores.length; i++)
{
System.out.print(scores[i] + " ");
}
-------------------------------------------------------------------------------
查找数组中的最大值:
int max = scores[0];////让max等于数组中第一个元素
for(int i = 1; i < scores.length; i++)
{
if(max < scores[i])
{
max = scores[i];//谁比他大,他就变成谁
}
}
System.out.println("最大值是" + max);
练习:现在有如下一个数组:
int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
要求将以上数组中的0项去掉,将不为0的值存入一个新的数组,生成新的数组为
int newArr[]={1,3,4,5,6,6,5,4,7,6,7,5};
public class Test {
public static void main(String[] args) {
int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
int[] buff = new int[100];
int j = 0;
for (int i = 0; i < oldArr.length; i++)
{
if (oldArr[i] != 0)
{
buff[j] = oldArr[i];
j++;
}
}
System.out.print("{");
for (int i = 0; i < j; i++)
{
if (i < j - 1)
{
System.out.print(buff[i] + ",");
}
else
{
System.out.print(buff[i]);
}
}
System.out.print("}");
}
}
作者:豆约翰
链接:https://www.jianshu.com/p/3bacbcb9bdec
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。