2013-05-06 64 views
0

我正在編寫一個控制檯應用程序,它使用散列表計算各種價格。它用一個叫Priceprint的類來寫價格。我爲程序的其餘部分使用哈希表,因爲順序不是特別重要,但是它在創建列表作爲輸出之前命令鍵。它通過將鍵放入向量中,按順序將它們排序,使用Collections.sort()排序向量,然後手動交換具有密鑰交換和特殊項的第一個和第二個鍵。然後它使用Enumeration從矢量中獲取所有內容,並調用另一個函數將每個條目寫入屏幕。用集合加Java排序加手工排序

public void out(Hashtable<String, Double> b, Hashtable<String, Double> d) { 
      Vector<String> v; 
      Enumeration<String> k; 
      String te1, te2, e; 
      int ex, sp; 

      v = new Vector<String>(d.keySet()); 
      Collections.sort(v); 

      te1 = new String(v.get(0)); 
      ex = v.indexOf("exchange"); 
      v.set(ex, te1); v.set(0, "exchange"); 

      te2 = new String(v.get(1)); 
      ex = v.indexOf("special"); 
      v.set(ex, te2); v.set(1, "special"); 

      if (msgflag == true) 
        System.out.println("Listing Bitcoin and dollar prices."); 
      else { 
        System.out.println("Listing Bitcoin and dollar prices, " 
             + message + "."); 
        msgflag = true; 
      } 

      k = v.elements(); 
      while (k.hasMoreElements()) { 
        e = new String(k.nextElement()); 
        out(e, d.get(e), b.get(e)); 
      } 
    } 

現在的問題是我碰到過缺乏單獨的思想是,交換條目和它的鍵排序按字母順序排列的列表。所以當我運行程序交換時,特殊的位於頂部,但列表的其餘部分不再按順序排列。我可能不得不放棄通過代碼輸入列表的單個條目的基本設計,這些條目的價格和特殊價格都是特殊的,但是與列表的每個其他方面都有排序。這太遺憾了,因爲它幾乎都可能需要去,我真的很喜歡這個設計。

下面是完整的代碼,不理我使用的是一類構造函數顯然應該使用靜態方法的事實,但忽視了:http://pastebin.com/CdwhcV2L

下面是一個使用Printprice創建價格清單的代碼測試程序的其他部分也Printprice名單:http://pastebin.com/E2Fq13zF

輸出:

[email protected]:~/devel/java/pricecalc$ java backend.test.Test 
I test CalcPrice, but I also test Printprice(Hashtable, Hashtable, String). 
Listing Bitcoin and dollar prices, for unit test, check with calculator. 
Exchange rate is $127.23 (USDBTC). 
Special is 20.0%. 
privacy: $2.0 0.0126BTC, for unit test, check with calculator. 
quotaband: $1.5 0.0094BTC, for unit test, check with calculator. 
quotahdd: $5.0 0.0314BTC, for unit test, check with calculator. 
shells:  $5.0 0.0314BTC, for unit test, check with calculator. 
hosting: $10.0 0.0629BTC, for unit test, check with calculator. 

回答

1

這個問題似乎是你把第一和第二要素還給我到「交換」和「特殊」來自的位置的矢量,而不是從矢量中移除「交換」和「特殊」並將它們插入矢量的頂部。

正確地做到這一點對於使用LinkedList而不是Vector來說效率更高。爲了執行所需的操作,假設vList

v.add(0, v.remove(v.indexOf("special"))); 
v.add(0, v.remove(v.indexOf("exchange"))); 

這應該放在「交換」首先,列表的「特殊」第二個,其餘的將留在排序順序之後。

+0

謝謝!這使得它很好,很簡單。 – 2013-05-06 21:18:57