Java “的ArrayIndexOutOfBoundsException;“圣诞节十二天”;字符串数组赋值

Java “的ArrayIndexOutOfBoundsException;“圣诞节十二天”;字符串数组赋值,java,string,indexoutofboundsexception,Java,String,Indexoutofboundsexception,我被指派编写一个程序,不使用循环就打印“圣诞十二天”的歌词(递归是可以的),我想我已经有了,但我一直收到这个 java.lang.ArrayIndexOutOfBoundsException: -1 我已经修改了我的if语句和编号,但是我问了几个朋友,我似乎无法指出问题所在 public class TwelveDays{ public static void main(String[] args){ Twelve_Days(0); } public static void Twel

我被指派编写一个程序,不使用循环就打印“圣诞十二天”的歌词(递归是可以的),我想我已经有了,但我一直收到这个

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);
    }
}
}
公共课十二天{
公共静态void main(字符串[]args){
十二天(0);
}
公共静态无效十二天(整数天){
字符串[]天={“第一”、“第二”、“第三”、“第四”、“第五”、“第六”、“第七”、“第八”、“第九”、“第十”、“第十一”、“第十二”};
System.out.println(“在“+天[天]+”圣诞节我的真爱游戏给我”);
十二份礼物(一天);
day++;

//如果(天你应该放置一个contion来停止递归

n==0
时,应该停止它

查看以下代码的n==0时将发生什么:

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

public static void Twelve_Gifts(int n) {

您将避免
java.lang.ArrayIndexOutOfBoundsException:-1的异常


你要从
n
中减去1,所以你要先检查
n
是否为正。

你的问题在于十二份礼物法——一旦你到达了“梨树中的鹧鸪”,你就不能阻止它递归

public static void Twelve_Gifts(int n) {
public static void Twelve_Gifts(int n) {

    if(n ==0)
    {
        return;
    }
if (n < 12) {
    Twelve_Gifts(n - 1);
}
if (n > 0) {
    Twelve_Gifts(n - 1);
}