/*
编码:字符串变成字节数组。
String-->byte[]; str.getBytes();//默认的编码表-gbk
str.getBytes(String charsetName);//传入编码方式
解码:字节数组变成字符串。
byte[]-->String; new String(byte[]);
new String(byte[],String charsetName);
gbk:4个字节
utf-8:6个字节
*/
import java.util.*;
class EncodeDemo{
public static void main(String[] args) {
String s = "你好";
byte[] b = s.getBytes();//编码
String s1 = new String(b);//解码
System.out.println(Arrays.toString(b));
}
}
/*
练习:
有五个学生,每个学生有3门课的成绩,
从键盘输入以上数据(包括姓名,三门课成绩),
输入的格式:如:zhangsan,30,40,60,计算出总成绩,
并把学生的信息和计算出的总分数高低顺序存放在磁盘文件“stu.txt”中。
1.描述学生对象。
2.定义一个可操作学生对象的工具类。
思想:
1.通过获取键盘录入一行数据并将改行数据中的信息取出封装成学生对象。
2.因为学生对象有很多,就需要存储,使用到集合。因为要对学生的总分排序,
所以可以使用TreeSet。
3.将集合的信息写入到文件中。
*/
import java.io.*;
import java.util.*;
class Student implements Comparable<Student>//强制让学生具备比较性{
private String name;
private double ch;
private double ma;
private double en;
private double sum;
Student(String name,double ch,double ma,double en){
this.name = name;
this.ch = ch;
this.ma = ma;
this.en = en;
sum = ma + ch + en;
}
public String getName(){
return name;
}
public double getSum(){
return sum;
}
public int compareTo(Student s)//元素自身具有比较性,重写compareTo方法。{
double num = new Double(this.sum).compareTo(new Double(s.sum));//主要条件
if(num == 0)
return this.name.compareTo(s.name);//次要条件,此处的compareTo是String类中的。
return num;
}
public int hashCode(){
return name.hashCode()+sum*78;
}
public boolean equals(Object obj){
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");
Student s = (Student)obj;
return this.name.equals(s.name) && this.sum == sum;
}
public String toString(){
return "student["+name+","+ch+","+ma+","+en+"]";
}
}
class StudentInfoTool{
public static Set<Student> getStudents_moren()throws IOException{
return getStudents(null);
}
public static Set<Student> getStudents(Comparator<Student> cmp)
throws IOException{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
String line = null;
Set<Student> students = null;
if(cmp == null)
students = new TreeSet<Student>();
else
students = new TreeSet<Student>(cmp);
while((line = br.readLine()) != null){
if("over".equals(line))
break;
String[] info = line.split(",");
Student student = new Student(info[0],Double.parseDouble(info[1]),
Double.parseDouble(info[2]),Double.parseDouble(info[3]));
students.add(student);
}
br.close();
return students;
}
public static void writeToFile(Set<Student> students){
BufferedWriter bw = new BufferedWriter(new FileWriter("stu.txt"));
for(Student student : students){
bw.write(student.toString()+"\t");
bw.write(student.getSum()+"");
bw.newLine();
bw.flush();
}
bw.close();
}
}
class StudentInfoTest{
public static void main(String[] args)throws IOException{
Comparator<Student> cmp = Collections.reverseOrder();
Set<Student> students = StudentInfoTool.getStudents(cmp);
StudentInfoTool.writeToFile(students);
}
}
学生对象成绩排序(Comparable)
最新推荐文章于 2024-10-29 16:57:44 发布