【问题标题】:Java - get index ids from array by valueJava - 按值从数组中获取索引ID
【发布时间】:2016-01-12 19:00:43
【问题描述】:

我有这个方法:

public int index(String character)
{
    String[] array = {"Apple", "Banana", "Apple", "Orange"};
    return Integer.parseInt(array.indexOf(character));
}

然后:

testClass ind = new testClass();
for (loop probably here)
{
    System.out.println(ind.index("Apple"));
}

结果应该是:

0 2

但我不知道应该在哪里放置循环以及应该在循环中放置什么。没有循环是结果只有第一个索引 id - 在这种情况下它将是 0。

【问题讨论】:

  • 你为什么要解析一个 int 的索引。它返回第一个索引... indexOf 即... for 循环的意义何在?
  • 是的,这是真的,对不起。你能告诉我应该把循环放在哪里吗?
  • 你想用这个实现什么?输入应该是什么,输出应该是什么?
  • 数组上没有 indexOf 这样的函数,所以它甚至不会编译。

标签: java


【解决方案1】:

不确定你想用你的代码做什么......但是你可以得到 0 2 作为输出的方式是......

static String[] array = {"Apple", "Banana", "Apple", "Orange"};

public static void main(String[] args) {
      for(int i = 0; i < array.length; i++)
          if(array[i].equals("Apple"))
             System.out.println(i);
}

不确定你的代码的目标是什么......所以这是我能给你的最多的

【讨论】:

  • 谢谢,这正是我想要的!如果我有这个:System.out.println(new String("acac").indexOf("a"));,我怎样才能得到 0 和 2?再次排名。
  • 我不需要获取唯一字符的数量,而是获取字符串中字母的位置。
【解决方案2】:
index = Arrays.asList(list).indexOf("element to search");

【讨论】:

  • 这是在浪费资源
  • 我只是写了一个小程序来测试它。 Arrays.asList(array).indexOf("xxx");快得多。 (~factor 10)确定它需要更多资源,但列表仍然是一种非常数据类型,所以你不会识别它
  • 很高兴能对您在这里所做的事情进行某种解释。
  • ` int elem = 10000;字符串 [] 数组 = 新字符串 [elem];长开始= System.currentTimeMillis(); for(int i=0; i
  • 抱歉,我是新来的,我认为 `` 会将其标记为代码
猜你喜欢
  • 1970-01-01
  • 2016-05-06
  • 2021-12-10
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2015-04-24
  • 1970-01-01
相关资源
最近更新 更多