2016-11-28 10 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

に答えます。次のシグネチャを使用して1つのメソッドを作成します。public boolean isPalindrome(String word)。あなたのメソッド 'isPalindrome(String、String、String)'を取り除く。メソッドがクラス内にあり、別のメソッドではないことを確認してください。 –

+0

私は彼らがちょうど1文字列を使用することを見ますが、私のプログラムは3を持っていますか?何をすべきかわからない –

答えて

2

を使用しています:

まず、あなたは、新しいStringを構築し、それが等しいかどうかをチェックより。

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

これはうまくいきますが、なぜ1文字列しか必要ないのですか? –

+0

それはアルゴリズムだけで、3つのパラメータを入力する必要はありません.3つの文字列をチェックしたい場合は、この関数を別のパラメータで3回呼び出します。 – keronconk

+0

これは1つだけの文字を受け取ります –

関連する問題