什么是数组?数据是可以装一组数据的变量

1.定义数组



float[] arr1 = new float[10];     // 可以装10个float数据
int[] arr2 = new int[10]; // 可以装10个int数据
String[] arr2 = new String[10]; // 可以装10个String数据


 2.数组赋值



arr1[0]=10.1       // 给float数组赋值
arr2[0]=10 // 给int数组赋值
arr3[0]="Logan" // 给String数组赋值


 

3.实战演练

3.1 根据用户输入求和与平均数

需求描述:

  用户输入5个成绩,然后求出这5个成绩的和与平均成绩

代码实现:



package cn.test.logan.day02;

import java.util.Scanner;

public class ArrayDemo {
public static void main(String[] args) {

Scanner scn = new Scanner(System.in);
//定义一个数组
float[] ScoreArray = new float[5];

// for循环为数组赋值
for(int i=0;i<5;i++) {
System.out.println("请输入学生成绩:");
String score = scn.nextLine();
ScoreArray[i]= Float.parseFloat(score);
}
// 计算总成绩
float sum = 0;
for(int i=0;i<5;i++) {
sum += ScoreArray[i];
}
System.out.println("总成绩为:"+sum);
System.out.println("平均成绩为:"+sum/5);
}
}


 

3.2 构造一个1,2,3...10的数组,然后逆序打印数组



package cn.test.logan.day02;

/**
* 使用for循环实现逆序打印数组
* @author QIN
*
*/
public class ArrayDemo1 {
public static void main(String[] args) {
int[] arr = new int[11];
// for循环实现
for(int i=0;i<arr.length;i++) {
arr[i] = i;
}
// 打印数组
for(int j=arr.length-1;j>0;j--) {
System.out.println(arr[j]);
}
System.out.println("----------------------------------");
}
}


 

3.3 求一组数的最大值与最小值



package cn.test.logan.day02;

public class ArrayDemo2 {
public static void main(String[] args) {
int[] arr = new int[5];
arr[0]=0;
arr[1]=10;
arr[2]=20;
arr[3]=30;
arr[4]=40;

//求最小值
int temp = arr[0];
for(int i=1;i<arr.length;i++) {
if(temp>arr[i]) {
temp=arr[i];
}
}
System.out.println("最小值为:"+temp);
//求最大值
temp = arr[0];
for(int i=1;i<arr.length;i++) {
if(temp<arr[i]) {
temp=arr[i];
}
}
System.out.println("最大值为:"+temp);
}
}


作者:奔跑的金鱼