练习1:将错乱拍虚的歌词,只能找正确顺序排好
题外话推荐一首好听的音乐:向文涛的《心病》
解法1:
package a03test;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Test4 {
public static void main(String[] args) throws IOException {
//1.读取数据
BufferedReader br = new BufferedReader(new FileReader("Test\\xb.txt"));
String line;
ArrayList<String> list = new ArrayList<>();
while ((line = br.readLine()) != null) {
list.add(line);
}
//2.排序
//按照每一行前面的序号进行排列
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
//获取o1和o2的序号
int i1 = Integer.parseInt(o1.split("\\.")[0]);
int i2 = Integer.parseInt(o2.split("\\.")[0]);
return i1-i2;
}
});
//3.写出
BufferedWriter bw=new BufferedWriter(new FileWriter("Test\\result.txt"));
for (String str : list) {
bw.write(str);
bw.newLine();
}
bw.close();
}
}
运行结果:
解法2:
package a03test;
import java.io.*;
import java.util.*;
public class Test5 {
public static void main(String[] args) throws IOException {
//1.读取数据
BufferedReader br = new BufferedReader(new FileReader("Test\\xb.txt"));
String line;
TreeMap<Integer,String> tm=new TreeMap<>();
while ((line = br.readLine()) != null) {
String[] arr = line.split("\\.");
tm.put(Integer.parseInt(arr[0]),line);
}
br.close();
//2.写出数据
BufferedWriter bw=new BufferedWriter(new FileWriter("Test\\result2.txt"));
Set<Map.Entry<Integer, String>> entries = tm.entrySet();
for (Map.Entry<Integer, String> entry : entries) {
String value = entry.getValue();
bw.write(value);
bw.newLine();
}
bw.close();
}
}
运行结果:
练习2:软件运行次数
实现一个验证程序运行次数的小程序,
要求:当程序运行超过三次给出提示:本软件只能免费使用3次,欢迎您注册会员后继续使用
程序运行演示如下:
第一次运行控制台输出:欢迎使用本软件,第1次使用免费~
第二次运行控制台输出:欢迎使用本软件,第2次使用免费~
第三次运行控制台输出:欢迎使用本软件,第3次使用免费~
第四次及之后运行控制台输出:本软件只能免费使用3次,欢迎您注册会员后继续使用~
package a03test;
import java.io.*;
public class Test6 {
public static void main(String[] args) throws IOException {
//1.把文件中的数字读取到内存中
BufferedReader br=new BufferedReader(new FileReader("Test\\count.txt"));
String line=br.readLine();
int count = Integer.parseInt(line);
//表示当前软件又运行了一次
count++;
//2.判断<=3正常运行
if(count<=3){
System.out.println("欢迎使用本软件,第" +count+ "次使用免费~");
}else{
System.out.println("本软件只能免费使用3次,欢迎您注册会员后继续使用~");
}
//3.把文件自增的count写出到文件
BufferedWriter bw=new BufferedWriter(new FileWriter("Test\\count.txt"));
bw.write(count+"");
bw.close();
br.close();
}
}
运行结果: