Can you find the needle in the haystack?
Write a function findNeedle() that takes an array full of junk but containing one "needle"
After your function finds the needle it should return a message (as a string) that says:
"found the needle at position " plus the index it found the needle
public class Kata {
public static String findNeedle(Object[] haystack) {
for (int i = 0; i < haystack.length; i++) { //假如5个string组成了[],那么length就是5,但是index是从0到4的!
if (haystack[i] == "needle") {
return "found the needle at position " + i; //needle的位置是定死的,所以用==也是可以的
}
}
return "needle be lost, yo";
}
}
public class Kata {
public static String findNeedle(Object[] haystack) {
int i = 0;
while(!String.valueOf(haystack[i]).equals("needle")){
i++;
}
return "found the needle at position " + i;
}
}
Can you find the needle in the haystack?Write a function findNeedle() that takes an array full of junk but containing one "needle"After your function finds the needle it should return a message (as a string) that says:"found the needle at position ".