2016-11-28 145 views
1

我想用布爾值來檢查字符串是否是迴文。我收到一個錯誤,不知道我做錯了什麼。我的程序已經有3個字符串,以前由用戶估算。謝謝你,我也用java檢查字符串是否爲迴文

public boolean isPalindrome(String word1, String word2, String word3){ 

int word1Length = word1.length(); 
int word2Length = word2.length(); 
int word3Length = word3.length(); 

for (int i = 0; i < word1Length/2; i++) 
{ 
    if (word1.charAt(i) != word1.charAt(word1Length – 1 – i)) 
    { 
     return false; 
} 
} 
return isPalindrome(word1); 
} 

for (int i = 0; i < word2Length/2; i++) 
{ 
if (word2.charAt(i) != word2.charAt(word2Length – 1 – i)) 
    { 
     return false; 
    } 
} 
return isPalindrome(word2); 
} 
for (int i = 0; i < word3Length/2; i++) 
{ 
if (word3.charAt(i) != word3.charAt(word3Length – 1 – i)) 
{ 
return false; 
} 
} 
return isPalindrome(word3); 
} 

    // my output should be this 
if (isPalindrome(word1)) { 
    System.out.println(word1 + " is a palindrome!"); 
    } 
    if (isPalindrome(word2)) { 
    System.out.println(word2 + " is a palindrome!"); 
    } 
    if (isPalindrome(word3)) { 
    System.out.println(word3 + " is a palindrome!"); 
    } 
+1

看一看這個蘇答案http://stackoverflow.com/questions/4138827/check-string-for-palindrome –

+1

你把所有的作品在那裏,你只是有一些語法錯誤,我很肯定。只需使用以下簽名'public boolean isPalindrome(String word)'製作1個方法。擺脫你的方法'isPalindrome(String,String,String)'。確保你的方法是在一個類中,而不是另一個方法。 –

+0

我看到他們只使用1個字符串,但我的程序有3個?不知道該怎麼辦 –

回答

2

你可以做它的方法是這樣的:

首先,建立一個新的字符串比你檢查它是否等於。

private static boolean test(String word) { 
    String newWord = new String();  
    //first build a new String reversed from original 
    for (int i = word.length() -1; i >= 0; i--) {   
     newWord += word.charAt(i); 
    }  
    //check if it is equal and return 
    if(word.equals(newWord)) 
     return true;   
    return false;  
} 

//You can call it several times 
test("malam"); //sure it's true 
test("hello"); //sure it's false 
test("bob"); //sure its true 
+0

這有效,但我很困惑,爲什麼它只需要一個字符串? –

+0

這只是因爲算法,你不需要你的函數來輸入3個參數,如果你想檢查3個字符串,只需要用不同的參數調用這個函數3次 – keronconk

+0

它只接收一個參數 –