【发布时间】:2014-07-18 18:08:13
【问题描述】:
对于这个作业,我认为我做对了,但是当我在线提交时,即使我使用 Eclipse 进行检查,它也没有将其列为正确。
提示:
编写一个 isPalindrome 方法,它接受一个字符串数组作为其参数,如果该数组是一个回文数组(如果它向前读取和向后读取相同)则返回 true,否则返回 /false。例如,数组 {"alpha", "beta", "gamma", "delta", "gamma", "beta", "alpha"} 是回文,因此将该数组传递给您的方法将返回 true。具有零个或一个元素的数组被认为是回文。
我的代码:
public static void main(String[] args) {
String[] input = new String[6]; //{"aay", "bee", "cee", "cee", "bee", "aay"} Should return true
input[0] = "aay";
input[1] = "bee";
input[2] = "cee";
input[3] = "cee";
input[4] = "bee";
input[5] = "aay";
System.out.println(isPalindrome(input));
}
public static boolean isPalindrome(String[] input) {
for (int i=0; i<input.length; i++) { // Checks each element
if (input[i] != input[input.length-1-i]){
return false; // If a single instance of non-symmetry
}
}
return true; // If symmetrical, only one element, or zero elements
}
作为一个例子,{"aay", "bee", "cee", "cee", "bee", "aay"} 在 Eclipse 中返回 true,但是 Practice-It!说它返回错误。怎么回事?
【问题讨论】:
-
顺便说一下,你的
for循环只能从0循环到input.length/2(含)。
标签: java arrays palindrome