数组的一些基本概念,要学会如何去定义一个数组:
使用数组四步走:
(1)声明数组:int []a;
(2)分配空间:a=new int[5];
(3)赋值:a[0]=8;
(4)处理数据:a[0]=a[0]*10;
数组定义:
数据类型 数组名 [];
数据类型 []数组名;(常用)
int []score={1,2,2.3,5,8,6,4...};
int []score=new int[]{1,2,5,4...};(当你赋值的时候不能指定数组的长度,当为了给数组分配空间时可以标明数组长度)
int scores[](int []score)=new int[数组长度];
增强型for循环:
for(int score(变量名,用来存放从数组scores中拿出来的每一个数据) : scores){
sum += score;
}
增强for代表依次把数组scores当中的数据拿出来赋值给score。
数组中Arrays类的使用:
Arrays.sort(数组名);对数组数据进行升序排序;
Arrays.toString(数组名);对数组数据元素输出;
Arrays.equals((数组1)(数组2));对两个数组进行比较,相同输出true,不相同输出false;
Arrays.fill((数组),(78));将数组元素全部换成值78。
int index = Arrays.binarySearch(数组名,要查找的数组元素下标),进行查找之前必须
使用Arrays.sort将数组进行升序排列然后进行查找数组下标。
下面给大家附上一个简单的数组的例子:
需求:定义一个数组,让用户输入四家店的价格,并存放在数组中,然后比较大小,找出其中价格最低的店
import java.util.Scanner;
public class Phone {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
int[]cost = new int[4];
System.out.println("请输入4家店的价格");
for(int i=0;i<cost.length;i++){
System.out.print("第"+(i+1)+"家店的价格:");
cost[i] = input.nextInt();
}
for(int i=0;i<cost.length-1;i++){
for(int j=i+1;j<cost.length;j++){
if(cost[i]>cost[j]){
int temp;
temp = cost[i];
cost[i] = cost[j];
cost[j] = temp;
}
}
}
int min = cost[0];
System.out.print("最低的价格是:"+min);
}
}
本文介绍了数组的基本概念及使用方法,包括数组声明、空间分配、赋值和数据处理等步骤。此外,还详细讲解了如何利用增强型for循环遍历数组、使用Arrays类进行排序和查找等操作。
4404

被折叠的 条评论
为什么被折叠?



