簡體   English   中英

Java中數組排序的問題

[英]Problems with sorting an Array in Java

我是一個該死的初學者,試圖編寫一個小程序來檢查 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");
    }

}

這應該可以解決問題:

  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");
    }       
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM