2013-12-10 44 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”“,你不会阻止它的递归