-2

I have this method:

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

And then:

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

And result should be:

0 2

But I don't know where I should put loop and what should be in loop. Without loop is result only first index id - in this case it would be 0.

2 Answers2

3

Not sure what you want to do with your code... But the way you can get 0 2 as an output is...

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);
}

Not sure what your goal is with your code... so that's the most I can give you

Ya Wang
  • 1,758
  • 1
  • 19
  • 41
  • Thanks, that is exactly what I wanted! And if I would have this: System.out.println(new String("acac").indexOf("a"));, how can I get 0 and 2? Again number of position. – Frank Hamasyona Jan 12 '16 at 19:27
  • http://stackoverflow.com/questions/22597527/counting-unique-characters-in-a-string-given-by-the-user – Ya Wang Jan 12 '16 at 19:31
  • I don't need get count of unique characters, but number positions of letter in string. – Frank Hamasyona Jan 12 '16 at 19:35
0
index = Arrays.asList(list).indexOf("element to search");
osanger
  • 2,276
  • 3
  • 28
  • 35
  • This is a waste of resources – Clashsoft Jan 12 '16 at 19:17
  • I just worte a small program to test it. Arrays.asList(array).indexOf("xxx"); is much faster. (~factor 10) sure it needs more resources but a list is still a very datatype, so you wouldn't recognize it – osanger Jan 12 '16 at 20:29
  • It would be nice to have some sort of explanation of what you're doing here. – Erick G. Hagstrom Jan 12 '16 at 21:56
  • ` int elem = 10000; String[] array = new String[elem]; long start= System.currentTimeMillis(); for(int i=0; i < elem; i++) array[i] =((int)( Math.random()*5000))+""; for(int i = 0; i < array.length; i++) if(array[i].equals("15")){ System.out.println(i); break; } System.out.println("As Array:"+(System.currentTimeMillis()- start)); start= System.currentTimeMillis(); int index = Arrays.asList(array).indexOf("15"); System.out.println("As List:"+(System.currentTimeMillis()- start));` – osanger Jan 12 '16 at 22:00
  • Sorry im new here thought `` will mark this as a code – osanger Jan 12 '16 at 22:00