2013-05-06 62 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