[英]Bubble sort lines of a file (Java)
I am trying to find a way to bubble sort a text file that looks like this:我正在尝试找到一种对看起来像这样的文本文件进行冒泡排序的方法:
04/26/16 Sega 3D Classics Collection 07/14/16 Batman: Arkham Underworld 06/24/16 Tokyo Mirage Sessions #FE
Essentially I want them to be in the order of release date for example a game released on 01/25/16 would come before a game released in 06/26/16 and it would create a new file like this:本质上我希望它们按照发布日期的顺序排列,例如 2016 年 1 月 25 日发布的游戏将在 2016 年 6 月 26 日发布的游戏之前发布,它会创建一个像这样的新文件:
04/26/16 Sega 3D Classics Collection 06/24/16 Tokyo Mirage Sessions #FE 07/14/16 Batman: Arkham Underworld
I am certain that there will be a for loop involved as each line will be an element of an array with swapping methods and a temporary value for comparison sake to swap the order of the but I cannot think of a way to write the new order into a new file.我确信将涉及一个 for 循环,因为每一行都是具有交换方法的数组的一个元素和一个临时值以进行比较以交换顺序,但我想不出一种将新顺序写入的方法一个新文件。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main (String[]args) throws IOException{
File file = new File("releasedates.txt");
String[]arr;
arr = input(file);
output(file,arr);
}
public static String[]input (File file) throws FileNotFoundException{
String[]arr = new String[3];
Scanner sc = new Scanner(file);
for(int i = 0; i < arr.length; i++){
arr[i] = sc.nextLine();
}
return arr;
}
public static void output(File file, String[] info) throws IOException{
FileWriter writer = new FileWriter("fileName.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
public static void sortByMonth(String[]info){
String temp;
for (int j = 0; j < info.length; j++) {
for (int i = j + 1; i < info.length; i++) {
if (info[i].compareTo(info[j]) < 0) {
temp = info[j];
info[j] = info[i];
info[i] = temp;
}
}
}
}
}
Just invoke the sortByMonth
inside your output
method: Also, there is no need to pass the File
object to output
as it is not used.只需在output
方法中调用sortByMonth
即可:此外,无需将File
object 传递给output
,因为它未使用。
public static void output(String[] info) throws IOException{
sortByMonth(info);
FileWriter writer = new FileWriter("fileName.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.