问题 D: 对象排序II

题目描述

已经编写好了以下主类.  请编写Student类,包含String类型 的 域 name, int类型的域 age, setNameAge(String name, int age)方法 , sortByName方法 (对参数列表中的学生数组,按照姓名的字典序 由小到到 排序) 。 

import java.util.*;
public class Main
{
     public static void main(String[] args)
     {
            Scanner r = new Scanner(System.in);
            String name;
            int age;
            int n;
            if( !r.hasNextInt() )  
                 return;
            n = r.nextInt(); 
            if( n <= 0 )  
                 return;
            Student []stu = new Student[n];
            for(int i = 0; i < n; i++)
            {
                    name = r.next(); 
                    if( !r.hasNextInt() )  
                          return;
                    age = r.nextInt(); 
                    if( age < 0 )  
                         return;;
                    stu[i] = new Student();
                    stu[i].setNameAge(name, age);
            }
            Student.sortByName(stu);
            for(Student s:stu)
                System.out.println(s.name + " " + s.age); 
        }    
}

输入

首先输入学生数目n,然后再依次输入n位同学的姓名和年龄

输出

按学生姓名字典序从小到大输出

样例输入

4
Tom 12
Bob 9
Kelly 13
Rose 10

样例输出

Bob 9
Kelly 13
Rose 10
Tom 12

我的方法:使用String类的compareTo方法比较name,按字典顺序比较

//定义Student类
class Student{
	//成员变量
	public String name;
	public int age;
	//成员方法
	public void setNameAge(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public static void sortByName(Student stu[]) {
		Student x = new Student();
		for(int i=0;i<stu.length;i++) {
			for(int j=i+1;j<stu.length;j++) {
				if(stu[i].name.compareTo(stu[j].name)>0) {
					x = stu[i];
					stu[i] = stu[j];
					stu[j] = x;
				}
			}
		}
	}
}

朋友的方法:用equals方法比较String类name,啊反正很绕,我看不太懂,不管他了

class Student
{
	String name;
	int age;
	
	void setNameAge(String name,int age)
	{
	
			this.name = name;
			this.age = age;	
		
	}
	static void sortByName(Student stu[])
	{
		ArrayList<String> list=new ArrayList<String>();
		for(int i=0;i<stu.length;i++)
		{
			list.add(stu[i].name);
		}
		Collections.sort(list);
		for(int j=0;j<stu.length;j++)
		{
			for(int k=j;k<stu.length;k++)
			{
				if(list.get(j).equals(stu[k].name))
				{
				
					Student s=stu[j];
					stu[j]=stu[k];
					stu[k]=s;
				
				}
			}
		}
		
	
	}
	
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值