题目:A1、定义一个Person类(name,age,job),初始化Person对象数组,有3个Person对象数组,并按照age从大到小进行排序,以及用名字的长度去排序,提示,使用冒泡排序法。
分析:
1、先定义Person类,初始化其对象数组。
2、可以通过冒泡排序法去完成,不熟悉冒泡排序可以先看一下我之前的这篇冒泡排序的经典例题,冒泡排序经典例题
3、冒泡排序要特别注意其循环次数,下面可通过分析去码代码:
public class Test {
public static void main(String[] args) {
Person[] person = new Person[3];//定义一个对象数组来存放各个对象
person[0] = new Person("jack", 30, "讲师");
person[1] = new Person("tom", 20, "学生");
person[2] = new Person("simith", 55, "教授");
//排序之前的顺序
System.out.println("==============排序之前的顺序=============");
for (int i = 0; i < person.length; i++) {
System.out.println(person[i].toString());
}
System.out.println();
//年龄从小到大排序后的顺序
System.out.println("==============年龄排序后的顺序=============");
Person person1 = null;//定义一个中间变量进行冒泡排序
for (int i = 0; i < person.length-1 ; i++) {//外层循环,数组长度为3,下标从0开始
for (int j = 0; j < person.length-i; j++) {//内层循环,最外面一层是定下来的,相当于一共三层,但是只进行两次比较
if (person[i].getAge()>=person[i+1].getAge()){
person1 = person[i];
person[i] = person[i+1];
person[i+1] = person1;
}
}
}
for (int i = 0; i < person.length; i++) {
System.out.println(person[i].toString());
}
System.out.println();
//按照名字长度从短到长排序
System.out.println("==============年龄排序后的顺序=============");
for (int i = 0; i < person.length-1 ; i++) {//外层循环,数组长度为3,下标从0开始
for (int j = 0; j < person.length-i; j++) {//内层循环,最外面一层是定下来的,相当于一共三层,但是只进行两次比较
if (person[i].getName().length()>=person[i+1].getName().length()){
person1 = person[i];
person[i] = person[i+1];
person[i+1] = person1;
}
}
}
for (int i = 0; i < person.length; i++) {
System.out.println(person[i].toString());
}
System.out.println();
}
}
class Person{
private String name;
private int age;
private String job;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", job='" + job + '\'' +
'}';
}
public Person(String name, int age, String job) {
this.name = name;
this.age = age;
this.job = job;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}