[英]Why won't it recognize my method?
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”,即使我在代碼的前面定義了它。 我怎么了 謝謝
您正在對String對象“ temp”調用反向。 您已經在Word
類中定義了reverse
方法,因此需要在Word
對象上調用它。
問題是您正在將temp設置為字符串,但是反向方法不是在字符串類內部,而是在您的類內部,但是當您執行此操作時,您試圖在字符串中找到它
temp.reverse();
您可以通過使reverse方法接受一個字符串並返回一個字符串來解決此問題,它所接受的字符串就是要反轉的字符串,而return是反轉的字符串。
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;
}
您應該使用
new StringBuilder(original).reverse().toString()
為了得到相反的結果。 字符串類型中不存在反向方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.