[英]Palindrome Recursion - Infinite loop
當我嘗試運行該程序時,將發生無限循環。 我不能說問題出在主要方法還是在遞歸方法中。
這是遞歸方法。
public class RecursivePalindrome
{
public boolean isPalindrome(String s)
{
if(s.length() <= 1)
{
return true;
}
else if(s.charAt(0) == s.charAt(s.length() - 1))
{
return isPalindrome(s.substring(1,s.length() - 1 ));
}
else
{
return false;
}
}
}
這是主要方法。
public class RecursivePalindromeTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a word or phrase. Type Q to quit: ");
String word = in.next();
RecursivePalindrome object = new RecursivePalindrome();
while(!word.equalsIgnoreCase("Q"))
{
if(object.isPalindrome(word))
{
System.out.println(word + " is a palindrome");
}
else
{
System.out.println(word + " is not a palindrome");
}
}
System.out.print("Enter another word or phrase. Type Q to quit: ");
word = in.next();
}
}
看來您永遠無法擺脫main方法中的while循環。
您應該將這兩行移動到while循環中,以便用戶可以輸入其他內容或鍵入“ q”退出:
System.out.print("Enter another word or phrase. Type Q to quit: ");
word = in.next();
您的問題在於此行:
while(!word.equalsIgnoreCase("Q"))
{
if(object.isPalindrome(word))
{
System.out.println(word + " is a palindrome");
}
else
{
System.out.println(word + " is not a palindrome");
}
}
System.out.print("Enter another word or phrase. Type Q to quit: "); //problem
word = in.next();
您正在運行while循環,沒有任何更新
已更正:
while(!word.equalsIgnoreCase("Q"))
{
if(object.isPalindrome(word))
{
System.out.println(word + " is a palindrome");
}
else
{
System.out.println(word + " is not a palindrome");
}
System.out.print("Enter another word or phrase. Type Q to quit: ");
word = in.next();
}
就像一個建議一樣,查找Java編碼約定,例如{通常留在一行的末尾,而不是單獨放在行尾,將您的代碼稍微基於這些約定可以使其他人更容易閱讀
這個惡性循環是無限的
while(!word.equalsIgnoreCase("Q"))
{
if(object.isPalindrome(word))
{
System.out.println(word + " is a palindrome");
}
else
{
System.out.println(word + " is not a palindrome");
}
}
while循環一直循環,直到將單詞設置為“ Q”為止,並且這種情況發生在循環外部,請放置以下代碼:
System.out.print("Enter another word or phrase. Type Q to quit: ");
word = in.next();
在while循環結束時
簡單的解決方案:您將}放在錯誤的位置(只是忘記了將word變量的更新包含在while循環中)。 所以只是一個錯字:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a word or phrase. Type Q to quit: ");
String word = in.next();
RecursivePalindrom object = new RecursivePalindrom();
while(!word.equalsIgnoreCase("Q"))
{
if(object.isPalindrome(word))
{
System.out.println(word + " is a palindrome");
}
else
{
System.out.println(word + " is not a palindrome");
}
// } old postion of the brace
System.out.print("Enter another word or phrase. Type Q to quit: ");
word = in.next();
} // new position of the brace
}
問題是您從主循環之后的輸入中得到了下一個單詞。 因此,這個詞不會改變並且永遠循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.