2016-12-13 123 views
0
import java.lang.String; 
public class Word 
{ 
    /** 
    * constructs a Word with String value s 
    * @param s is string value of Word 
    */ 
    public Word(String s) 
    { 
     original = s; 
    } 

    /** 
    * reverses letters in original string 
    * @return a string that is a reverse of original 
    */ 
    public String reverse() 
    { 
     String temp = original; 
     String areverse = ""; 
     int x; 
     for (x = temp.length() ; x>0 || x==0 ; x --) 
     { 
      areverse = temp.substring(x); 
     } 
     return areverse; 
    } 

    /**  
    * determines is word is a palindrome 
    * @return true if word is a palindrome, false otherwise 
    */ 
    public boolean isPalindrome() 
    { 
     boolean flag = false; 
     String temp = original; 
     if (temp.equals(temp.reverse())) 
      flag = true; 
     return flag; 

    } 

    /** 
    * Alternate method to determine if word is a palindrome 
    * @return true if word is a palindrome, false otherwise  
    */ 
    public boolean isPalindrome2() 
    { 
     String temp = original; 
     int x = temp.length(); 
     boolean flag = false; 
     int y = 0; 
     while (temp.subtring(y).equals(temp.substring(x)) && (x>0 || x==0)) 
     { 
      x--; 
      y++; 
     } 
     if (x==0) 
      flag=true; 
     return flag; 


    } 

    private String original; 
} 

我必須編寫這個程序來查找單詞的反轉,並以兩種不同的方式確定單詞是否是迴文。我只給了方法名稱和方法的評論,但方法中的所有代碼都是我的。當我在第一個迴文方法中使用reverse()方法時,bluej告訴我它找不到變量或方法'reverse',儘管我在代碼中早先定義了它。我的問題是什麼?謝謝爲什麼不識別我的方法?

+0

這不包括,但是這是在頂部導入java.lang.String; public class Word { public word(String s) { original = s; } – rxTT

+1

[橡皮鴨調試](http://www.rubberduckdebugging.com/)會在這裏很長的路要走。 – rmlan

+0

我想我們需要查看實際報告錯誤的位置(您在調用'reverse()'方法的位置)。 – markspace

回答

0

的問題是,你設置溫度爲一個字符串,但是相反的方法不是字符串類裏面,而是你的類,但你試圖找到它在字符串中,當你做了

temp.reverse(); 

你可以通過使reverse方法接受一個字符串並返回一個字符串來解決這個問題,它接受的字符串是它的反轉,返回是反轉的字符串。

public String reverse(String string) 

然後調用方法在你的類

if (temp.equals(reverse(temp))) 
    flag = true; 

因此,新的反向方法看起來像

public String reverse(String string) 
{ 
    String areverse = ""; 
    for (int x = string.length(); x>0; x--) 
    { 
     areverse += string.charAt(x - 1); 
    } 
    return areverse; 
} 
+0

我不能改變方法,但我會做到這一點,只需要幾個點。儘管謝謝! – rxTT

+0

如果它需要一個點,你可以嘗試 如果(temp.equals(reverse())flag = true; – FacelessTiger

1

您正在調用String對象「temp」的反轉。您已在Word類中定義reverse - 方法,因此您需要在Word對象上調用它。

+0

gotchya ...那我該怎麼做? – rxTT

+0

您可以通過Word實例化一個新的Word對象myNewWordObject = new Word(「someString」)。然後你可以在該對象上調用reverse:myNewWordObject.reverse()。在你的isPalindrome方法中,它可能看起來像:if(temp.equals(new Word(temp).reverse())) – Stefan

0

您應該使用

new StringBuilder(original).reverse().toString() 

爲了取得相反的結果。字符串類型中不​​存在反向方法。

+0

我們不能使用StringBuilder – rxTT

+0

你的方法不會工作方法reverse在Word類中定義,而不是String類。 – Stefan

相關問題