黑马程序员技术交流社区
标题:
从键盘录入学生信息并保存到本地
[打印本页]
作者:
余旋
时间:
2015-11-9 13:56
标题:
从键盘录入学生信息并保存到本地
要求以名字,数学成绩,语文成绩,英语成绩的格式进行录入,保存在stuInfo.txt文件中,发出来交流学习一下
package com.jwis.cos;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Set;
import java.util.TreeSet;
public class StuFileSave {
public static void main(String[] args) throws IOException {
Set<Student> stuInfo = StuInfo.InfoInput();
StuInfo.InfoSave(stuInfo);
}
}
class StuInfo
{
public static Set<Student> InfoInput() throws IOException
{
Set<Student> temp = new TreeSet<Student>();
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line=bufr.readLine())!=null)
{
if("over".equals(line))
break;
String[] stuInfo = line.split(",");
temp.add(new Student(stuInfo[0],
Integer.parseInt(stuInfo[1]),
Integer.parseInt(stuInfo[2]),
Integer.parseInt(stuInfo[3])));
}
return temp;
}
public static void InfoSave(Set<Student> stuInfo) throws IOException
{
BufferedWriter bufw = new BufferedWriter(new FileWriter("C:\\Users\\lx\\Desktop\\stuInfo.txt"));
for(Student info : stuInfo)
{
String Info = info.toString();
bufw.write(Info);
bufw.newLine();
}
bufw.close();
}
}
class Student implements Comparable<Student>
{
private String name;
private int math,chinese,english;
private int sum;
public Student(String name,int math,int chinese,int english) {
// TODO Auto-generated constructor stub
this.name = name;
this.math = math;
this.chinese = chinese;
this.english = english;
this.sum = (this.math+this.chinese+this.english);
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
int temp = o.sum-this.sum;
if(temp==0)
return this.name.compareTo(o.name);
return temp;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return (this.name.hashCode()+this.sum*31);
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(!(obj instanceof Student))
throw new ClassCastException("比较类型不对");
Student temp =(Student)obj;
if(this.name == temp.name)
return this.sum==temp.sum;
return false;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "student["+this.name+"]"+"\t"+"sum["+this.sum+"]";
}
}
复制代码
作者:
lvcj
时间:
2015-11-9 21:51
1.compareTo()方法中修改
2.没注释
3.写入方法没刷新
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2