简体   繁体   中英

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:

 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.

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM