簡體   English   中英

使用方法(Java)按字母順序對文件內容進行排序

[英]Alphabetically sort contents of file using methods (Java)

標題可能有點誤導,但我正在編寫一段代碼,將其作為文本文件的內容:

 04/26/16 Sega 3D Classics Collection 07/14/16 Batman: Arkham Underworld 06/24/16 Tokyo Mirage Sessions #FE

本質上,我希望它們按字母順序排列,它應該創建一個如下所示的全新文件:

 Batman: Arkham Underworld Sega 3D Classics Collection Tokyo Mirage Sessions #FE

我嘗試的是使用 indexOf() 方法從我現有的文本文件中僅提取游戲列表的名稱。 我還嘗試將它們存儲在一個新數組中以避免計算機混淆。 問題是,當我嘗試將 info 數組的 indexOf 存儲到新數組中時,該行給出了“無法從 int 轉換為字符串”的錯誤,我不確定如何修復該錯誤。

這是我下面的代碼:

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 = input(file);

    output(file,arr);

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

  public static void outputSort1(File file,String[] info) throws IOException{
    sortByMonth(info);
    FileWriter writer = new FileWriter("fileNameSorted1.txt");
    for(String aString:info){
        writer.write(aString);
    }
    writer.close();
}

public static void sortByName(String[]info){

    String[] names = new String[3];

      for(int i = 0; i < info.length; i ++){

          names[i] = info[i].indexOf(" " ,info.length);
      }

    String temp;

      for (int j = 0; j < names.length; j++) {
        for (int i = j + 1; i < names.length; i++) {
   
    if (names[i].compareTo(names[j]) < 0) {
      temp = names[j];
      names[j] = names[i];
      names[i] = temp;
          }
       }
      }
    }

}

您已將名稱數組聲明為String[] ,因此您不能將 integer 分配給它。 indexOf 方法返回 integer。

public static void sortByName(String[]info) {
    String[] names = new String[3];   //<-- declaration suggests store string
    for (int i = 0; i < info.length; i++) {
        names[i] = info[i].indexOf(" ", info.length);//<-you are assigning integer
    }

我認為你正在嘗試做的是這樣的:

names[i] = info[i].substring(info[i].indexOf(" "), info[i].length());

使用java.nio API 進行文件實現,因為java.io API 已過時。 此外,如果您使用 Stream 操作,那么實現會變得容易得多:

public class Test {
    public static void main(String[] args) throws Exception {
        Path file = Path.of("e:\\releasedates.txt");
        List<String> records = Files.readAllLines(file);

        List<String> sortedByName = records.stream()
                .map(s -> s.substring(s.indexOf(" "), s.length()))
                .sorted(String::compareTo)
                .collect(Collectors.toList());
        System.out.println(sortedByName);
        Files.write(Path.of("e:\\fileNameSorted.txt"), sortedByName);

        List<String> sortedByDate = records.stream().sorted(Test::compareDates)
                .map(s -> s.substring(s.indexOf(" "), s.length()))
                .collect(Collectors.toList());
        System.out.println(sortedByDate);
        Files.write(Path.of("e:\\fileDateSorted.txt"), sortedByDate);
    }

    public static int compareDates(String d1, String d2) {
        d1 = d1.substring(0, d1.indexOf(" "));
        d2 = d2.substring(0, d2.indexOf(" "));
        LocalDate ld1 = LocalDate.parse(d1,
                DateTimeFormatter.ofPattern("MM/dd/yy"));
        LocalDate ld2 = LocalDate.parse(d2,
                DateTimeFormatter.ofPattern("MM/dd/yy"));

        return ld1.compareTo(ld2);
    }
}

@onkar ruikar 的回答是正確的。 indexOf返回int並且您試圖將其存儲在String中。 我想擴展他的答案,您可以將游戲/電影名稱存儲在TreeSet而不是Array中,因此默認情況下它將按字母順序排序。

如果您想允許重復的游戲/電影名稱,則可以使用ArrayList並調用Collections.sort(<array list>)方法,該方法將按字母順序對ArrayList進行排序。

這是我們如何在 Java 中對Collections進行排序的詳細答案: https://stackoverflow.com/a/8725470/3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM