数组
4.1 什么是数组?
- 容器
- 可以存多个同种类型的数据
4.2 Java中如何表示数组
- 定义数组
- 数据类型[] 数组名;
- 实例化数组
-
public class Main { public static void main(String[] args) { int[] arryList = new int[7]; for (int i = 0 ;i<7;i++){ arryList[i] =i*2; System.out.println(arryList[i]); } } }
- 实例化数组
- 静态赋值
- 动态赋值
-
数组名 = new 数据类型[长度]
-
4.3
练习
//1.键盘录入5个数存入数组 public class One { public static void main(String[] args) { int[] arry =new int [5]; System.out.println("请输入数据!"); Scanner sc =new Scanner(System.in); for (int i=1;i<6;i++){//循环键入数据 System.out.println("请第"+i+"次输入数据!"); int a =sc.nextInt(); arry[i-1]=a;//给数组赋值 } for (int i = 0 ;i<5;i++){//循环赋值并取出 System.out.println("第"+(i+1)+"次输入数据是"+arry[i]); } } }
//取数 package arrylistTrain; public class Two { public static void main(String[] args) { int[] arryList = new int[7];//定义数组 for (int i = 0 ;i<7;i++){//循环赋值并取出 arryList[i] =i*2; System.out.println(arryList[i]); } }
public class Three { public static void main(String[] args) { int[] arry =new int [5]; System.out.println("请输入数据!"); Scanner sc =new Scanner(System.in); for (int i=1;i<6;i++){//循环键入数据 System.out.println("请第"+i+"次输入数据!"); int a =sc.nextInt(); arry[i-1]=a;//给数组赋值 } int max=arry[0]; for (int i=1;i<5;i++){ if (max>=arry[i]){ System.out.println("第"+(i)+"次比较max为"+max); }else { max=arry[i]; System.out.println("第"+(i)+"次比较max为"+max); } } } }
public class Four { public static void main(String[] args) { int[] arry =new int [5]; System.out.println("请输入数据!"); Scanner sc =new Scanner(System.in); for (int i=1;i<6;i++){//循环键入数据 System.out.println("请第"+i+"次输入数据!"); int a =sc.nextInt(); arry[i-1]=a;//给数组赋值 } int min=arry[0]; for (int i=1;i<5;i++){ if (min<=arry[i]){ System.out.println("第"+(i)+"次比较min为"+min); }else { min=arry[i]; System.out.println("第"+(i)+"次比较max为"+min); } } } }
import java.util.Scanner; //冒泡排序 public class Five { public static void main(String[] args) { int[] arry =new int [5]; System.out.println("请输入数据!"); Scanner sc =new Scanner(System.in); for (int i=1;i<6;i++){//循环键入数据 System.out.println("请第"+i+"次输入数据!"); int a =sc.nextInt(); arry[i-1]=a;//给数组赋值 } int n =arry.length; for (int i = 0;i<n;i++){//外层循环次数,等于数组长度 for (int j = 0;j<5-(i+1);j++){//内层循环次数,每次冒泡确定一个最大数在数组末尾,每次内层循环比较次数少1 int middle;//中间变量 if (arry[j]>arry[j+1]){//冒泡交换顺序 middle=arry[j]; arry[j]=arry[j+1]; arry[j+1]=middle; } } } for (int i = 0 ;i<5;i++){//循环赋值并取出 System.out.println(arry[i]); } } }