目录
1.冒泡排列学员成绩(降序)
2.常用Arrays类的应用
2.1.sort
2.2.equals
2.3.toString
2.4.fill
2.5.Arrays.copyOf
2.6.binarySearch
3.利用二维数组计算成绩
1.冒泡排列学员成绩(降序)
package ch06;
import java.util.Arrays;
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
//练习1:冒泡排列学员成绩(降序)
System.out.println("请输入5名学员的成绩:");
Scanner sc = new Scanner(System.in);
int scores[]=new int[5];
//循环录入五名学员的成绩
for(int i=0;i<5;i++) {
scores[i]=sc.nextInt();
}
System.out.println(Arrays.toString(scores));
//冒泡排序
for(int i =0;i<scores.length-1;i++) {
for(int j =0;j<scores.length-1-i;j++) {
int temp =0;
if(scores[j]<scores[j+1]) {
temp = scores[j];
scores[j] = scores[j+1];
scores[j+1] = temp;
}
}
}
System.out.println(Arrays.toString(scores));
}
}
2.常用Arrays类的应用
2.1.sort
对数组进行升序排序
int nums[]= {90,8,11,44,1};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
2.2.equals
比较数组中值是否相等
int arr1[] = {10,20,30,40};
int arr2[] = {10,20,30,40};
int arr3[] = {10,20,30};
System.out.println(Arrays.equals(arr1,arr2));
System.out.println(Arrays.equals(arr1,arr3));
2.3.toString
将数组转换为字符串
String name1[] = {"张三","李四"};
System.out.println(Arrays.toString(name1));
2.4.fill
将数组中所有元素替换为指定内容
String name2[] = {"张三","李四","王五"};
System.out.println(Arrays.toString(name2));
Arrays.fill(name2, "马六");
System.out.println(Arrays.toString(name2));
2.5.Arrays.copyOf
复制 浅拷贝(复制值)
int num1[] = {1,2,3,4,5};
int num2[] = Arrays.copyOf(num1, num1.length);
System.out.println(num1==num2);
System.out.println(Arrays.toString(num2));
2.6.binarySearch
在数组中查找指定值(数组必须升序),找不到返回负数。
int scores[] = {2,20,90,1,8};
Arrays.sort(scores);
int index = Arrays.binarySearch(scores, 1);
System.out.println("index=="+index);
3.利用二维数组计算成绩
package ch06;
import java.util.Scanner;
/**
*
* @author 94063
*
*/
public class Test03 {
public static void main(String[] args) {
/**
* 显示班级学生总成绩
* 已知有3个班级各5名学员,
* 请使用 二维数组计算各个班级的总成绩
**/
Scanner sc =new Scanner(System.in);
int arr1[][] = new int[3][5];
int sum[] = new int[3];
for(int i = 0;i<3;i++) {
System.out.println("***********第"+(i+1)+"个班*************");
for(int j = 0;j<5;j++) {
System.out.print("请输入第"+(j+1)+"个学生的成绩:");
int scores =sc.nextInt();
sum[i] += scores;
}
}
System.out.println("***********成绩统计*************");
System.out.println("1班总成绩:"+sum[0]);
System.out.println("2班总成绩:"+sum[1]);
System.out.println("3班总成绩:"+sum[2]);
}
}