2011-12-16 85 views
0
public class recursionExcercise4 
{ 

    public static void main (String[] args) 
    { 
    boolean statement=false; 
    String ch=""; 
    String a="I am bubbles who is a little slugger and loves apple and yellow." 
    BacktoBacks(a,ch,statement); 
    } 

    public static void BacktoBacks(String sentence, String ch, boolean statement) 
    { 
    String newLine="",word=""; 
    System.out.print(sentence.charAt(0)); 
    if(sentence.charAt(0)=='.') System.out.println(); 

    if(sentence.length()>1) 
    { 
     int num=sentence.substring(1).indexOf(" "); 
     word = sentence.substring(0,num); 
     System.out.println(word); 
    } 
    BacktoBacks(newLine,ch,statement); 
    } 
} 

這就是代碼。簡單遞歸問題退回方式

if語句循環中的行是我添加的,所以你可以改變它,但沒有別的東西可以改變。頂部的if語句必須保留在那裏。此外,我試圖避免循環,因爲它使它太容易了。任何方式來做到這一點?我嘗試過但需要幫助。

目標是打印出雙字母字符串中的單詞。這也應該向後打印。所以像這樣:

黃 蘋果 猛男 小 泡沫

你的幫助是非常讚賞。 謝謝!

+1

這聞起來像「家庭作業」。如果是這樣,請標記爲這樣。 – Bohemian 2011-12-16 00:56:49

+0

@Bohemian有不止一個觀點:http://meta.stackexchange.com/questions/34503/should-the-possible-homework-tag-be-discouraged – 2011-12-16 00:58:17

回答

2

所以你需要一個函數來檢查一個單詞是否包含雙字母,

public boolean hasDoubleLetters(String word){ 
    // test 
} 

,並根據其結果,遞歸調用後打印的字。你必須將正確的參數傳遞給遞歸調用。