java - 检查字谜时出现奇怪的比较问题

标签 java comparison

抱歉,这个标题太糟糕了;然而,我想不出更好的方式来总结我的困境。

在尝试解决涉及检查一个字符串是否是另一个字符串的字谜词的问题时,我实现了一种解决方案,该解决方案涉及从两个字符串中删除所有空格,将它们都转换为字符数组,对它们进行排序,然后查看它们是否是彼此平等。

如果是,程序打印出“Is an anagram.”,否则“Is not an anagram.”

问题是,即使我的代码编译成功并运行良好,但最终结果始终是“Is not an anagram.”,无论两个原始字符串是否确实是彼此的字谜。我插入的用于调试的快速代码表明,在具有实际字谜的情况下,我最终比较的两个字符数组显然是相同的,但比较的结果是错误的。

我无法准确说出为什么会发生这种情况,除非我忽略了一些非常明显的东西,或者在我比较的内容中存在一些额外的未显示的字符。

代码如下:

import java.util.Arrays;
import java.util.Scanner;
public class Anagram {
    public static void main(String[] args) {
        char[] test1;
        char[] test2;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter first phrase>");
        test1 = input.nextLine().replaceAll(" ", "").toCharArray();
        Arrays.sort(test1);
        System.out.print("Enter second phrase>");
        test2 = input.nextLine().replaceAll(" ", "").toCharArray();
        Arrays.sort(test2);
        if (test1.equals(test2)) {
            System.out.println("Is an anagram.");
        }
        else {
            System.out.println("Is not an anagram.");
        }
        /* debugging */
        System.out.println(test1);
        System.out.println(test2);
        System.out.println(test1.equals(test2));
    }
}

以及测试运行的结果输出:

Enter first phrase>CS AT WATERLOO
Enter second phrase>COOL AS WET ART
Is not an anagram.
AACELOORSTTW
AACELOORSTTW
false

非常感谢任何和所有帮助。

最佳答案

使用Arrays.equals()比较两个数组的方法。它将比较数组的元素,而默认的 Object.equals() 方法则不会。

Returns true if the two specified arrays of chars are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.

关于java - 检查字谜时出现奇怪的比较问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1895625/

相关文章:

java - 多次成功连接后无法创建与数据库服务器的连接

java - 测试后运行 Dataprovider

c++ - 如何以简单有效的方式比较 vector ?

xml - *您*如何在 Web 应用程序的世界中使用 XML?

java - 连接数据库 Spring Data JPA 时捕获异常

java - 多线程服务器共享ArrayList

c++ - 双重比较

algorithm - 找到两个二叉搜索树的公共(public)元素的最佳方法

file-io - 通过 CRC 比较文件

java - ValueAnimator 只重复一次