【发布时间】:2015-03-04 09:39:07
【问题描述】:
我正在尝试编写一个程序来检查一个单词是否是回文。我的代码可以编译,但 isItPalindrome 方法中的代码似乎根本没有运行。我希望有人能指出我哪里出错了。这是我的代码:
class Main
{
public static void main ( String args[] )
{
System.out.print ("#Enter word");
String word = BIO.getString();
String wordLowerCase = word.toLowerCase(); // converts word to lower case (only way i could think of to ignore case)
char letters[] = wordLowerCase.toCharArray(); // converts string into an array of character
while ( !word.equals ("END")){
if (isItPalindrome(letters) == true)
{
System.out.print (""+word+"");
System.out.println (" is a palindrome");
}
else if (isItPalindrome(letters) == false)
{
System.out.print (""+word+"");
System.out.println (" is not a palindrome");
}
System.out.print ("#Enter word");
word = BIO.getString();
}
}
public static boolean isItPalindrome ( char letters[]){
boolean palindrome = true;
if (letters.length%2 == 0){
for (int index=0; index<letters.length/2-1; index++) //index will finish at letters/2
{
if (letters[index] != letters[letters.length-index-1]) //checks if index is the same as its opposite letter
{
return false;
}
else //if any pairs of letters are not in ascending order then it returns fasle and breaks out of the loop
{
palindrome = true;
}
}
}
else{
for (int index = 0; index < (letters.length-1)/2-1; index++)
{
if (letters[index] != letters[letters.length-index-1]){
return false;
}
else{
palindrome = true;
}
}
}
return palindrome;
}
}
【问题讨论】:
-
似乎根本没有运行。你怎么知道?
-
另外,你永远不会更新
letters,所以你只有第一个单词的字母。 -
什么是 BIO (word = BIO.getString();)?
-
另外,删除
-1(所有三个)(并且您不需要根据letters.length%2制作2个不同的案例,因为letters.length%2 == 1->(letters.length-1)/2 == letters.length/2) -
尝试将 System.out.println() 添加到您的 isItPalindrome 中,并打印每个被比较字符的值。这样你就可以自己找出逻辑出了什么问题。此外,与其调用该方法两次,不如调用一次并将返回值分配给布尔值会更简单。
标签: java methods boolean palindrome arrays