引发ArrayOutOfBounds异常

时间:2018-12-11 05:16:21

标签: java

如果要在数组的头部或尾部添加文本,我想在其中添加文本,以将其移动一个索引。由于某种原因引发ArrayOutOfBounds异常,我什至尝试使用letter.length而不是直接使用数组长度为7。

public class ArrayInsert {
        public static void main(String args[])
        {

            String[] letter =  {"A","B","C","D","",""} ;
            //System.out.println(letter.length+1);
           Scanner sc = new Scanner(System.in);
           System.out.println("Enter the text you wanna add to the array!");
           String newtext= sc.nextLine();

           System.out.println("Type H to add text to the head of the array, or T to add it to the Tail");
           String ht=sc.nextLine();

           if("H".equals(ht))
           {
               if(letter[0]==null)
               {
                   letter[0]=newtext;
               }

               else
               {
                   for(int i=0;i<7;i++)
                   {
                       letter[i]=letter[i+1];
                   }
                   letter[0]=newtext;
               }

           }
       //head code ends


       if(  "T".equals(ht))
       {
           int tailnumber= 7+1;
           letter[tailnumber]=newtext;
       }
       //tail code ends
       for(int j=0;j<7;j++)
       {
           System.out.println(letter[j]);
       }

        }
                             }

0 个答案:

没有答案
相关问题