2013-12-10 46 views
-1

我被分配編寫一個程序,用於在不使用循環的情況下將歌詞打印到「聖誕節十二天」(遞歸是好的),並且我認爲我擁有它但我不斷收到這個ArrayIndexOutOfBoundsException爲字符串數組賦值「聖誕節十二天」

java.lang.ArrayIndexOutOfBoundsException: -1 

我修修補補和我的if語句和編號,但一對夫婦的朋友誰問我,我似乎無法查明問題。

public class TwelveDays{ 
public static void main(String[] args){ 
    Twelve_Days(0); 
} 

public static void Twelve_Days (int day){ 
    String[] days = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}; 

    System.out.println("On the " + days[day] + " day of Christmas my true love game to me "); 
    Twelve_Gifts(day); 

    day++; 
    //if(day <=12); 

    if(day < 12){ 
     Twelve_Days(day); 
    } 
} 

public static void Twelve_Gifts(int n){ 
    String[] gifts = {"A partridge in a pear tree", "Two turtle doves", "Three French hens", 
         "Four Calling birds", "Five golven rings", "Six geese a-laying", 
         "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", 
         "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming"}; 

    System.out.println(gifts[n]); 

    if(n < 12){ 
     Twelve_Gifts(n-1); 
    } 
} 
} 

當然,任何幫助表示讚賞,謝謝一堆!

回答

1

你應該把一個contion停止遞歸。

n ==0,你應該停止它。

參看N == 0時下面的代碼會發生什麼:

  if (n < 12) { 
      Twelve_Gifts(n - 1); 
    } 

n - 1 = -1,然後gifts[n]成爲gifts[-1],這引起了Exception

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 

變化

public static void Twelve_Gifts(int n) { 

public static void Twelve_Gifts(int n) { 

    if(n ==0) 
    { 
     return; 
    } 

,你會避免java.lang.ArrayIndexOutOfBoundsException: -1

3
if (n < 12) { 
    Twelve_Gifts(n - 1); 
} 

不同的是應該是:

if (n > 0) { 
    Twelve_Gifts(n - 1); 
} 

您從n減去1,所以您想要檢查n是否爲正。

0

你的問題在於Twelve_Gifts方法 - 一旦你到達「梨樹中的part」「,你不會阻止它的遞歸