【问题标题】:Finding Palindromes in an Array在数组中查找回文
【发布时间】: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


【解决方案1】:

这不是您在 Java 中比较字符串的方式。使用以下内容:

if (!input[i].equals(input[input.length-1-i])){
        return false; // If a single instance of non-symmetry
    }

阅读this

【讨论】:

    【解决方案2】:

    您不能使用运算符 == 或 != 来比较字符串对象。运算符将处理对象引用而不是值。

    public static boolean isPalindrome(String[] input) {
            for (int i=0; i<input.length; i++) { // Checks each element
                if (!input[i].equals( input[input.length-1-i])){
                    return false; // If a single instance of non-symmetry
                }
            }
            return true; // If symmetrical, only one element, or zero elements
    }
    

    【讨论】:

    • 如果它解决了您的问题,请不要忘记将答案标记为正确。
    猜你喜欢
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 2017-07-15
    • 2013-03-01
    相关资源
    最近更新 更多