【问题标题】:Struggling to identify where the logic error in my lexicographical sorting algorithm lies努力确定我的字典排序算法中的逻辑错误在哪里
【发布时间】:2019-12-13 13:32:01
【问题描述】:

我正在尝试编写一个操作股票交易的程序方法。我需要对我的输出进行排序,以便公司按字母顺序排序,同名资产类型(债券和股票)的公司按债券来股排序。例如,如果我有 Microsoft Bond、Apple Stock 和 Microsoft Stock,则输出应如下所示:

苹果股票、微软债券、微软股票

当我运行我的代码时,我得到了这个:

苹果股票、微软股票、微软债券

我曾尝试在比较符号之间切换,以防我倒退,但这只会使它离正确更远。

public int compareTo(Transaction t) {
    if (this.name.compareTo(t.name) == 0) 
    {
      if((this.assetType).compareTo(t.assetType) < 0)
        return -1;
      else if((this.assetType).compareTo(t.assetType) > 0)
        return 1;
      else
        return 0;
    }
    else if((this.name).compareTo(t.name) < 0) {
      return 1;
    }
    else {
      return -1;
    }
  }
}

【问题讨论】:

  • 你能提供更多关于assetType的信息吗?
  • assetType 是一个包含“Bond”或“Stock”的字符串

标签: java string algorithm sorting if-statement


【解决方案1】:

字段的顺序是相反的,即如果(this.assetType).compareTo(t.assetType) &lt; 0 => return -1; 和同时if((this.name).compareTo(t.name) &lt; 0) => return 1;。您将不得不反转其中之一,例如:

public int compareTo(Transaction t) {
    if (this.name.compareTo(t.name) == 0) 
    {
      if((this.assetType).compareTo(t.assetType) < 0)
        return -1;
      else if((this.assetType).compareTo(t.assetType) > 0)
        return 1;
      else
        return 0;
    }
    else if((this.name).compareTo(t.name) < 0) {
      return -1;
    }
    else {
      return 1;
    }
  }
}

P.S.:也没有验证,这可能很有用 - 检查 null 值、类型等。

【讨论】:

    猜你喜欢
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    相关资源
    最近更新 更多