2015-02-09 23 views
-1

昨天我問了一個問題關於迴文和Java:的Java程序迴文(1個錯誤)

Java Palindrome Program (am I on track)?

我已經取得了一些進展,到目前爲止所有你的幫助(非常感謝你再次多)。在我可以測試代碼之前,我只需要一點幫助。我正在使用Eclipse,並且在一行中出現錯誤(我將在下面的代碼中將錯誤作爲註釋加入)。我一直得到一個「無法在數組類型String []」上調用charAt(int)。

任何人都知道這裏發生了什麼?自從我使用Java以來​​已經有一段時間了。在大約12個月前在C.S. One中使用它,然後在Data Structures中繼續使用C++,然後在下一個課程中使用機器代碼和彙編語言。這裏的代碼(我也包括代碼中的評論中的錯誤)。非常感謝:

public class Palindrome 
{ 

public boolean isPalindrome(String theWord) 
{  
    for (int i = 0; i < theWord.length(); i++) { 
     if (theWord.charAt(i) != theWord.charAt (theWord.length() - i - 1)) { 
      return false; 
     } 
    } 
    return true; 
} 


public static void main(String [] theWord) 
{ 
     int leftPointer = 0; 
     int rightPointer = theWord.length - 1; 

     for (int i = 0; i < theWord.length/2; i++) { 
      while (leftPointer >= rightPointer) { 
       if (theWord.charAt(i) == theWord.charAt (theWord.length - i - 1)) { // Error: Cannot invoke charAt(int) on the array type String[] 
        leftPointer++; 
        rightPointer--; 
       } 
       System.out.println(theWord); 
      } 
     } 
} 

}

+3

該錯誤似乎很明顯。 'charAt'是一個String方法而不是一個String數組方法。 – sprinter 2015-02-09 02:15:52

+0

'theWord'是一個(可能)多個「字符串」的數組。 'charAt'只能應用於一個'String'。 – ajb 2015-02-09 02:16:22

+0

你的意思是'theWord [i] .charAt' – sprinter 2015-02-09 02:16:29

回答

1

您正在嘗試一個的String [](字符串傳遞給你的程序的參數數組)上訪問的charAt(),但你需要在訪問一個字符串。我的世界建議是這樣:

if (theWord[i].charAt(0) == theWord[theWord.length - i - 1].charAt (0)) {

這可能會幫助你。

0

charAt(int index)應用於String而不是String數組。你的程序想要決定一個字符串是否是迴文,比如「abcba」。而不是檢查一個字符串數組是否都是迴文,對不對?例如{「abcba」,「bbc」,「aba」}。

0

在Java(如在C++)中的程序接收到的參數列表,這是一個字符串數組後。因此,您的班級應如下所示:

public class Palindrome 
{ 
    public static boolean isPalindrome(String theWord) 
    {  
    for (int i = 0; i < theWord.length(); i++) { 
     if (theWord.charAt(i) != theWord.charAt (theWord.length() - i - 1)) { 
     return false; 
     } 
    } 
    return true; 
    } 


    public static void main(String [] args) 
    { 
    String theWord = args[0]; // first word passed to the program 
    boolean isPalindrom = Palindrome.isPalindrome(theWord); 
    System.out.println(theWord + " is" + (isPalindrom ? "" : " NOT ") + " a Palindrome."); 
    } 

} 
+0

Hi Max Zoom。你能否解釋一下「String theWord = args [0]; boolean isPalindrom = Palindrome.isPalindrome(theWord);」部分代碼,特別是「Palindrome.isPalindrome(theWord)」。非常感謝。 – 2015-02-09 07:46:17