題目
編寫(xiě)一個(gè)方法findNeedle()
來(lái)找出array中的一個(gè)"needle"
。
在你的函數(shù)找到針后纯陨,它應(yīng)該返回一條字符串:"found the needle at position "
加上它發(fā)現(xiàn)針時(shí)的index位置猪叙,所以:
Java
findNeedle(new Object[] {"hay", "junk", "hay", "hay", "moreJunk", "needle", "randomJunk"})
應(yīng)該返回
"found the needle at position 5"
測(cè)試用例:
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";
}
}
別人家的:
真的很簡(jiǎn)潔橘沥。
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"));
}
}
小結(jié)
又豐富我對(duì)庫(kù)函數(shù)的了解indexOf()喉祭。