编写Student类,有两个成员变量:姓名(name)和身高(height)。
要求该类通过实现Comparable接口规定该类的对象的大小关系,按height(身高)值的大小确定大小关系,即:学生按其身高确定相互之间的关系。
使用链表添加多个Student对象,使用Collection调用sort方法将链表中的对象按其height值排序,并将按身高排序后的学生信息保存到文件。存入文件后,文件格式如下:
姓名 身高
张三 178
李四 188
周五 198
实现按照身高值查找学生的功能。
注意:数据的输入和输出方式自行选择。
在第二次使用迭代器的时候,迭代器已经到达链表的尾部,所以hasNext()方法返回false。因此,我创建了第二个迭代器。
在查阅了java的api文档之后,我发现了可以使用Interface ListIterator。其中的boolean hasPrevious()方法可以反向遍历。省去了构建第二个迭代器对象的麻烦。
下面是代码
import java.util.*;
import java.io.*;
public class main
{
public static void main(String[] args)
{
Student stu1 = new Student("张三",178);
Student stu2 = new Student("周五",198);
Student stu3 = new Student("李四",188);
LinkedList<Student>list = new LinkedList<Student>();
list.add(stu1);
list.add(stu2);
list.add(stu3);
Collections.sort(list);
Iterator<Student>iter = list.iterator();//获取迭代器对象
try
{
FileWriter in = new FileWriter("Sudent.txt");
BufferedWriter inTwo = new BufferedWriter(in);
inTwo.write("姓名 身高");
inTwo.newLine();
while (iter.hasNext())
{
Student stu = iter.next();
String temp = stu.name + " " + stu.height;
inTwo.write(temp);
inTwo.newLine();
}
inTwo.flush();
inTwo.close();
}
catch(IOException e)
{
System.out.printf("File Input Error" + e);
}
System.out.print("请输入您要查找的学生的身高:");
int found, flag = 0;
Scanner input = new Scanner(System.in);
found = input.nextInt();
Iterator<Student>iter2 = list.iterator();
while (iter2.hasNext())
{
Student stu = iter2.next();
if (stu.height == found)
{
System.out.println("该学生为" + stu.name);
flag = 1;
}
}
if (flag == 0)
{
System.out.println("没有该学生");
}
}
}
class Student implements Comparable<Student>
{
String name;
int height;
Student(String n,int h)
{
this.name = n;
this.height = h;
}
public int getHeight()
{
return this.height;
}
public int compareTo(Student stu)
{
return this.height - stu.getHeight();
}
}