每日一练17——Java大海捞针找字符串(8kyu)

题目

编写一个方法findNeedle()来找出array中的一个"needle"

在你的函数找到针后,它应该返回一条字符串:"found the needle at position "加上它发现针时的index位置,所以:

Java

findNeedle(new Object[] {"hay", "junk", "hay", "hay", "moreJunk", "needle", "randomJunk"})

应该返回

"found the needle at position 5"

测试用例:

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class NeedleExampleTests {
  @Test
  public void tests() {
    Object[] haystack1 = {"3", "123124234", null, "needle", "world", "hay", 2, "3", true, false};
    Object[] haystack2 = {"283497238987234", "a dog", "a cat", "some random junk", "a piece of hay", "needle", "something somebody lost a while ago"};
    Object[] haystack3 = {1,2,3,4,5,6,7,8,8,7,5,4,3,4,5,6,67,5,5,3,3,4,2,34,234,23,4,234,324,324,"needle",1,2,3,4,5,5,6,5,4,32,3,45,54};
    assertEquals("found the needle at position 3", Kata.findNeedle(haystack1));
    assertEquals("found the needle at position 5", Kata.findNeedle(haystack2));
    assertEquals("found the needle at position 30", Kata.findNeedle(haystack3));
  }
}

解答

我的:

public class Kata {
  public static String findNeedle(Object[] haystack) {
    for(int i = 0; i < haystack.length; i++){
      if("needle".equals(haystack[i])){
        return "found the needle at position "+i;
      }
    }
    return "not found the needle at position";
  }
}

别人家的:

真的很简洁。

public class Kata {
  public static String findNeedle(Object[] haystack) {
    return String.format("found the needle at position %d", java.util.Arrays.asList(haystack).indexOf("needle"));
  }
}

小结

又丰富我对库函数的了解indexOf()。

你可能感兴趣的:(每日一练17——Java大海捞针找字符串(8kyu))