我需要一些幫助來理解我的代碼的「幕後」部分。我有一個技術援助助理部分代碼,所以我不完全確定它的部分功能。瞭解遞歸代碼
這裏是我的問題(我知道你應該單獨發佈多個問題,但在手,總體而言,這是一個很短的問題。這兩個形影相隨)
- 使用遞歸的方法,寫出來的字符串如果輸入了「雷達」這個詞,那麼每一步都要處理這個問題。對「稻草藝術」也一樣。因此,就像遞歸方法一步一步分解雷達和稻草藝術都是迴文一樣。那麼如果我將雷達輸入到我的程序中,它會如何看待幕後?
然後,我只是用一個簡短的迭代法做了迴文同樣的事情需要一些幫助:
- 使用迭代方法寫一些簡單的代碼(使用循環)來解決這個相同的問題。 (問題在於 - 實現一個使用遞歸方法的程序,該程序確定用戶輸入的字符串是否是迴文。如果字符串與前向相同,則爲迴文,如「雷達」或「塔科貓」)
這裏是我的代碼使用遞歸梅索德解決:
import java.util.Scanner;
public class RecursivePalindrome {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a word and I will determine if it is a palindrome");//Gets user input
String word = keyboard.nextLine();
String combined = word.replaceAll("[\\W]", "");//matches non-word characters, and removes the spaces.
combined = combined.toLowerCase();//makes the combined word all lowercase
if(checkPalindrome(word))//calls palindrome method and sees if combined word is a palindrome
{
System.out.println("The word " + word + " is a palindrome");
}
else
{
System.out.println("The word " + word + " is not a palindrome");
}
}
private static boolean checkPalindrome(String word)
{
if(word.length() <= 1)//if length is less than or equal to 1 then the string is palindrome
{
return true;
}
if(word.charAt(0) == word.charAt(word.length()-1))//checks the first and last char of the string
{
//if true, then does the same thing with substring
//returns only when the string is done checking
return checkPalindrome(word.substring(1, word.length()-1));
}
//if string doesn't pass check, it's not a palindrome
return false;
}
}
事實上,你沒有'?'是一個可能的跡象表明你的問題不清楚。你在問什麼?你不明白什麼? – Whymarrh
在運行我的程序時,我需要草編藝術和雷達如何成爲迴文的幫助。所以就像我的代碼一步一步分解到雷達文字,使其通過迴文測試。 – USC23