如何获取数组的索引

3
protected double[] cpi = { 10, 10.1, 10.3, 11.6, 13.7, 16.5 }
  protected CharSequence[] fromDate = { 
          "1914",
          "1915",
          "1916",
          "1917",
          "1918",
          "1919"};
  protected CharSequence[] toDate = { 
          "1914",
          "1915",
          "1916",
          "1917",
          "1918",
          "1919"};

我正在尝试以下操作:

double factor = cpi[frmDate[k]] / cpi [toDate[k]];

我对两者都遇到了以下错误:

类型不匹配:无法将CharSequence转换为int

类型不匹配:无法将CharSequence转换为int

我尝试的是... 如果fromDate的选择是索引=2,而toDate的选择是索引=3,则计算以下内容:
double factor = cpi[10.3] / cpi[11.6];

1
你认为 cpi[10.3] 是什么意思? - Sotirios Delimanolis
1
你需要使用元素的索引位置,而不是实际的元素值,所以更像是 cpi[2]/cpi[3] - kabuto178
cpi[10.3] 是一个示例,展示了应该有什么,但我明白你的意思 :) - Si8
@SotiriosDelimanolis 的意思是:[] 之间的部分是查找的索引。 10.3 怎么可能是一个索引呢?换句话说,如果有人让你喝第 10.3 杯啤酒,你会怎么做? - MH.
正如@kabuto178所说,应该是cpi[2]/cpi[3],但我在问题示例中显示了值,而不是索引,以帮助理解。 - Si8
显示剩余2条评论
2个回答

3
您可能需要这个:
protected double[] cpi = { 10, 10.1, 10.3, 11.6, 13.7, 16.5 }
  protected CharSequence[] fromDate = { 
          "1914",
          "1915",
          "1916",
          "1917",
          "1918",
          "1919"};
  protected CharSequence[] toDate = { 
          "1914",
          "1915",
          "1916",
          "1917",
          "1918",
          "1919"};
String year1 = "1915";
String year2 = "1918";
indexYear1 = Arrays.asList(fromDate).indexOf(year1); //find the position (index) of year1 => 1
indexYear2 = Arrays.asList(toDate).indexOf(year2); //find the position (index) of year2 => 4
double factor = cpi[indexYear1] / cpi[indexYear2]; // => 10.1 / 13.7

fromDatetoDate是选择索引,可以根据用户更改,从不固定。 - Si8
也许这个方法可行。如果x代表charsequence数组,那么我可以获取选择的值并将其匹配,然后得到索引?x代表charsequence变量吗? - Si8
1
它是O(n)的,因此非常高效。使用一些Map类可以将其变为O(log n),但在添加/删除时需要花费更多时间,达到O(n*log n)。 - libik
你的代码一开始就没有功能 :D,如果它能工作,那么它将是高效的 :)。 - libik
现在已经解决了,我采用了不同的方法。我的应用程序数组有更多内容,但导致计算出错的是...我在其中一个数组中缺少了一些值,所以它没有加起来!我接受了你的答案! - Si8
显示剩余2条评论

1

只需要这样做:

double factor = cpi[k] / cpi[j];

其中kfrmDate的选择索引,jtoDate的选择索引。

因为现在你正在尝试将字符串用作数组的索引。我假设你想使用相同的索引来访问cpi数组。

为了计算kj,创建一个函数getIndex(CharSequence[] array, CharSequence item)

下面是一些伪代码:

private int getIndex(CharSequence[] array, CharSequence item) {
    for(int a = 0; a < array.length; a++) {
        if array[a] is item
            return a;
    }
    return -1; //not in it
}

实际上,OP询问如何计算kj - harpun
我实际上在同时使用K,因此J没有发挥作用。 - Si8
假设您正在使用 frmDate[k],我认为OP已经知道了 k 是什么。虽然如果它们不直接对应,我会添加另一节。 - Clark
我正在使用K作为数组,但是根据选择进行不同的赋值。我认为问题就出在这里。 - Si8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接