2016-07-24 50 views
2

我有這個文本文件,我想基於來自對HC HC和排序P3如何從文本文件進行排序,並寫入到另一個文本文件的Java

這是我要排序的文件(avgGen.txt) :

7686.88,HC 
20169.22,P3 
7820.86,HC 
19686.34,P3 
6805.62,HC 
17933.10,P3 

然後我需要的輸出到一個新的文本文件(output.txt的)是:

6805.62,HC 
17933.10,P3 
7686.88,HC 
20169.22,P3 
7820.86,HC 
19686.34,P3 

我怎樣才能對排序從文本文件HC和P3,其中HC總是出現奇數指數P3出現偶數索引bu t我想根據HC值進行排序升序?

這是我的代碼:

public class SortTest { 
public static void main (String[] args) throws IOException{ 
    ArrayList<Double> rows = new ArrayList<Double>(); 
    ArrayList<String> convertString = new ArrayList<String>(); 
    BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt")); 

    String s; 
    while((s = reader.readLine())!=null){ 
     String[] data = s.split(","); 
     double avg = Double.parseDouble(data[0]); 
     rows.add(avg); 
    } 

    Collections.sort(rows); 

    for (Double toStr : rows){ 
     convertString.add(String.valueOf(toStr)); 
    } 

    FileWriter writer = new FileWriter("output.txt"); 
    for(String cur: convertString) 
     writer.write(cur +"\n"); 

    reader.close(); 
    writer.close(); 

    } 
} 

請幫助。

回答

2

當您從輸入文件讀取時,基本上放棄了字符串值。您需要保留這些字符串值並將它們與其相應的double值相關聯以達到您的目的。

您可以

  1. 包裹雙值和字符串值成一類,
  2. 使用,而不是double值類單獨
  3. 然後進行排序基於雙列表創建列表使用比較器的類的值或使類實現Comparable接口。
  4. 打印出兩個雙值及其相關聯的字符串值,其被封裝在一個類

下面內是一個例子:

static class Item { 
    String str; 
    Double value; 

    public Item(String str, Double value) { 
     this.str = str; 
     this.value = value; 
    } 
} 
public static void main (String[] args) throws IOException { 
    ArrayList<Item> rows = new ArrayList<Item>(); 
    BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt")); 

    String s; 
    while((s = reader.readLine())!=null){ 
     String[] data = s.split(","); 
     double avg = Double.parseDouble(data[0]); 
     rows.add(new Item(data[1], avg)); 
    } 

    Collections.sort(rows, new Comparator<Item>() { 

     public int compare(Item o1, Item o2) { 
      if (o1.value < o2.value) { 
       return -1; 
      } else if (o1.value > o2.value) { 
       return 1; 
      } 
      return 0; 
     } 
    }); 

    FileWriter writer = new FileWriter("output.txt"); 
    for(Item cur: rows) 
     writer.write(cur.value + "," + cur.str + "\n"); 

    reader.close(); 
    writer.close(); 
} 
+0

我已經改變了我的期望輸出,並且不知道如何根據HC和P3對而不是僅僅對它進行排序。我如何修復代碼?謝謝 – Ina

1

當您的程序從輸入文件中讀取行時,它會拆分每行,存儲double部分,並丟棄其餘部分。這是因爲只使用data[0],而不是任何表達式的一部分。

有幾種方法可以解決這個問題。一個是創建具有double價值和整個字符串對象的數組:

class StringWithSortKey { 
    public final double key; 
    public final String str; 
    public StringWithSortKey(String s) { 
     String[] data = s.split(","); 
     key = Double.parseDouble(data[0]); 
     str = s; 
    } 
} 

創建這個類,sort them using a custom comparator的對象或通過實現Comparable<StringWithSortKey>接口列表,排序的對象str成員寫出來進入輸出文件。

0

定義一個POJO或豆表示良好限定的/組織在文件/結構化數據類型:

class Pojo implements Comparable<Pojo> { 
    private double value; 
    private String name; 

    @Override 
    public String toString() { 
    return "Pojo [value=" + value + ", name=" + name + "]"; 
    } 

    public double getValue() { 
    return value; 
    } 

    public void setValue(double value) { 
    this.value = value; 
    } 

    public String getName() { 
    return name; 
    } 

    public void setName(String name) { 
    this.name = name; 
    } 

    /** 
    * @param value 
    * @param name 
    */ 
    public Pojo(double value, String name) { 
    this.value = value; 
    this.name = name; 
    } 

    @Override 
    public int compareTo(Pojo o) { 

    return ((Double) this.value).compareTo(o.value); 
    } 

} 

之後則:讀 - >排序 - >店:

public static void main(String[] args) throws IOException { 
    List<Pojo> pojoList = new ArrayList<>(); 
    BufferedReader reader = new BufferedReader(new FileReader("chat.txt")); 

    String s; 
    String[] data; 
    while ((s = reader.readLine()) != null) { 
     data = s.split(","); 
     pojoList.add(new Pojo(Double.parseDouble(data[0]), data[1])); 
    } 

    Collections.sort(pojoList); 

    FileWriter writer = new FileWriter("output.txt"); 
    for (Pojo cur : pojoList) 
     writer.write(cur.toString() + "\n"); 

    reader.close(); 
    writer.close(); 

    } 
0

使用,有一個簡單的方法來執行此操作。

public static void main(String[] args) throws IOException { 
    List<String> lines = 
    Files.lines(Paths.get("D:\\avgGen.txt")) 
     .sorted((a, b) -> Integer.compare(Integer.parseInt(a.substring(0,a.indexOf('.'))), Integer.parseInt(b.substring(0,b.indexOf('.'))))) 
     .collect(Collectors.toList()); 

    Files.write(Paths.get("D:\\newFile.txt"), lines); 
} 

更妙的是,使用方法參考

public static void main(String[] args) throws IOException { 
    Files.write(Paths.get("D:\\newFile.txt"), 
       Files.lines(Paths.get("D:\\avgGen.txt")) 
        .sorted(Test::compareTheStrings) 
        .collect(Collectors.toList())); 
} 

public static int compareTheStrings(String a, String b) { 
    return Integer.compare(Integer.parseInt(a.substring(0,a.indexOf('.'))), Integer.parseInt(b.substring(0,b.indexOf('.')))); 
} 
0

通過採用雙循環排序的項目 然後使用循環和右排定的順序只是comapre它

 public static void main(String[] args) throws IOException { 
       ArrayList<Double> rows = new ArrayList<Double>(); 
       ArrayList<String> convertString = new ArrayList<String>(); 
       BufferedReader reader = null; 
       try { 
        reader = new BufferedReader(new FileReader("C:/Temp/AvgGen.txt")); 
       } catch (FileNotFoundException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

       String s; 
      try { 
       while((s = reader.readLine())!=null){ 
        String[] data = s.split(","); 
        convertString.add(s); 
        double avg = Double.parseDouble(data[0]); 
        rows.add(avg); 
       } 
      } catch (NumberFormatException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      FileWriter writer = new FileWriter("C:/Temp/output.txt");; 
      Collections.sort(rows); 
       for (double sorted : rows) { 
        for (String value : convertString) { 
        if(Double.parseDouble(value.split(",")[0])==sorted) 
        { 

         writer.write(value +"\n"); 
        } 
       } 

      } 
相關問題