标签:学生 nbsp vat als size scanner 指定 this pareto
Java-数组
1、什么是数组?
数组是存储同一类型的数据的集合。
public class Students { private String name; private int credit; private int age; public Students(String name,int credit,int age){ this.name = name; this.credit = credit; this.age =age; } public void setName(String name){ this.name = name; } public String getName(){ return name; } public void setCredit(int credit){ this.credit = credit; } public int getCredit(){ return credit; } public void setaAge(int age){ this.age = age; } public int getAge(){ return age; } public void show(){ System.out.println("Name "+ name+" Credit " + credit+ " Age "+ age+"\n"); } }
然后在主方法里面建立一个学生数组,并且通过循环创建学生对象并且往里面输入信息
public static void main(String[] args){ String name; int age; int credit; System.out.println("请输入学生个数"); Scanner sc = new Scanner(System.in); int size = sc.nextInt(); Students[] stuarray = new Students[size]; for(int i = 0; i < stuarray.length;i++){ stuarray[i]=new Students(); System.out.println("请输入学生姓名"); name = sc.next(); stuarray[i].setName(name); // System.out.println(stuarray[i].getName()); System.out.println("请输入学生学分"); credit = sc.nextInt(); stuarray[i].setCredit(credit); System.out.println("请输入学生年龄"); age = sc.nextInt(); stuarray[i].setaAge(age); }
最后通过三大排序方法(选择排序、冒泡排序、插入排序)分别对其姓名、学分、年龄排序
public void sort1(Students[] stus){ for(int i = 0; i < stus.length - 1;i++) { int min_index = i; for(int j = i + 1; j < stus.length;j++){ if((stus[i].getName()).compareTo((stus[j].getName())) >0 ){ min_index = j; } } //这个地方能够成功转换吗?能! if(min_index != i){ Students temp = stus[min_index]; stus[min_index] = stus[i]; stus[i] = temp; } } } public void sort2(Students[] stus){ boolean a = true; while(a){ a = false; for(int i = 0; i < stus.length - 1;i++){ if(stus[i].getCredit() > stus[i+1].getCredit()){ Students temp = stus[i]; stus[i] = stus[i+1]; stus[i+1] = temp; a = true; } } } } public void sort3(Students[] stus){ for(int i = 1; i < stus.length;i++){ Students temp = stus[i]; int j = i - 1; for(;j >=0 && stus[j].getAge() > stus[i].getAge();j--){ stus[j+1] = stus[j]; } stus[j+1] = temp; } }
SortOfinformation a = new SortOfinformation(); a.sort1(stuarray); System.out.println("名字排序以后的输出"); a.showName(stuarray); a.sort2(stuarray); System.out.println("学分排序后输出"); a.showCredit(stuarray); a.sort3(stuarray); System.out.println("年龄排序后输出"); a.showAge(stuarray);
这样就完成了这个小练习了!
标签:学生 nbsp vat als size scanner 指定 this pareto
原文地址:https://www.cnblogs.com/782687539-nanfu/p/10325873.html