1、保存5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件
public class Students {
private String name;
private int mathScore;
private int englishScore;
private int chineseScore;
public Students(String name, int mathScore, int englishScore, int chineseScore) {
this.name = name;
this.mathScore = mathScore;
this.englishScore = englishScore;
this.chineseScore = chineseScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
public int getEnglishScore() {
return englishScore;
}
public void setEnglishScore(int englishScore) {
this.englishScore = englishScore;
}
public int getChineseScore() {
return chineseScore;
}
public void setChineseScore(int chineseScore) {
this.chineseScore = chineseScore;
}
@Override
public String toString() {
return "Students{" +
"姓名:'" + name + '\'' +
", 数学成绩:" + mathScore +
", 英语成绩:" + englishScore +
", 语文成绩:" + chineseScore +
", 总成绩:"+getSum()+
'}'+'\n';
}
public int getSum(){
return this.chineseScore+this.mathScore+this.englishScore;
}
}
public static void main(String[] args) throws IOException {
MyComparator myComparator=new MyComparator();
FileWriter fileWriter=new FileWriter("D:\\java2211\\2.txt");
TreeSet<Students> treeSet=new TreeSet<>(myComparator);
treeSet.add(new Students("张三",80,90,70));
treeSet.add(new Students("李四",90,90,90));
treeSet.add(new Students("王五",90,90,70));
fileWriter.write(treeSet.toString());
fileWriter.flush();
fileWriter.close();
}
}
class MyComparator implements Comparator<Students> {
@Override
public int compare(Students o1, Students o2) {
return o2.getSum()-o1.getSum();
}
2、打印数字,读取通知
(1)在main方法中启动两个线程;
(2)在1个线程循环打印100以内的整数;
(3)直到第2个线程从键盘读取了“Q”命令。
public class ThreadScanner extends Thread {
Scanner input = new Scanner(System.in);
private ThreadNum m;
public ThreadScanner(ThreadNum m){
this.m=m;
}
@Override
public void run() {
while(true){
System.out.println("请输入:");
char key = input.next().toUpperCase().charAt(0);
if(key=='Q'){
m.setFlag(false);
break;
}
}
}
}
public class ThreadNum extends Thread {
boolean flag=true;
@Override
public void run() {
while (flag){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
int x=(int) (Math.random()*100);
System.out.println("随机数:"+x);
}
}
public void setFlag(boolean flag){
this.flag=flag;
}
}
public class Print {
public static void main(String[] args) {
ThreadNum tnum=new ThreadNum();
ThreadScanner ts=new ThreadScanner(tnum);
tnum.start();
ts.start();
}
}