我是个流血的初学者,试图编写一个lil程序来检查2个单词是否是字谜。到目前为止,单词中的所有空格都已删除,但显然我的Arrays.sort()出现错误,但我看不到它。为什么我的Arrays.sort()行中的错误在哪里以及如何解决?
编辑:如果我不这样处理Arrays.sort(),则它可以编译和运行,因此显然这行只有一个问题。如果我将其留在其中,则指向数组并显示错误:找不到符号
public static void isAnagramm(String wordOne, String wordTwo)
{
String w1= wordOne.replaceAll("\\s", "");
int word1 = w1.length();
String w2 = wordTwo.replaceAll("\\s", "");
int word2 = w2.length();
boolean anagrammStatus = false;
if(word1 == word2)
{
anagrammStatus = true;
}
else
{
char [] charArrayWordOne = w1.toLowerCase().toCharArray();
char [] charArrayWordTwo = w2.toLowerCase().toCharArray();
//Arrays.sort(charArrayWordOne);
//Arrays.sort(charArrayWordTwo);
anagrammStatus = charArrayWordOne.equals(charArrayWordTwo);
}
if(anagrammStatus == false)
{
System.out.println("Anagram");
}
else;
{
System.out.println("No Anagram");
}
}
答案 0 :(得分:0)
这应该可以解决问题:
public static void isAnagramm(String wordOne, String wordTwo)
{
String w1= wordOne.replaceAll("\\s", "");
String w2 = wordTwo.replaceAll("\\s", "");
// No need to keep the length variables
boolean anagramStatus = false;
// Check if the strings are equal to begin with, use equals and not == operator
if(w1.equals(w2))
{
anagramStatus = true;
}
else
{
char [] charArrayWordOne = w1.toLowerCase().toCharArray();
char [] charArrayWordTwo = w2.toLowerCase().toCharArray();
Arrays.sort(charArrayWordOne);
Arrays.sort(charArrayWordTwo);
// Compare arrays using the Arrays.equals method to avoid comparing the object references
anagramStatus = Arrays.equals(charArrayWordOne, charArrayWordTwo);
}
// Use simple boolean logic in your condition here, or again, always use == instead of =
if (anagramStatus)
{
System.out.println("Anagram");
}
else
{
System.out.println("No Anagram");
}
}