【问题标题】:Insert element in array - JAVA在数组中插入元素 - JAVA
【发布时间】:2016-01-09 13:25:03
【问题描述】:

为什么会有 ArrayIndexOutOfBounds 异常..请澄清:) 我尝试更改数组的大小,但仍然无法创建成功的程序 导入 java.util.Scanner;

类插入 {

public static void main(String[]args) throws Exception
{
    Scanner sc = new Scanner(System.in);
    int a[]= new int[5];
    int i;


    for(i=0;i<a.length-1;i++)
    {
        System.out.println("Enter the Element : ");
        a[i]=sc.nextInt();

    }

    System.out.println("Enter the location for insertion : ");
    int loc = sc.nextInt();
    System.out.println("Enter the value for location : " +loc+" is");
    int value = sc.nextInt();

    for(i=a.length-1;i>loc;i--)
    {
        a[i+1]=a[i];
    }
    a[loc-1] = value;
    System.out.println("New Array is : ");

    for (i=0;i<=a.length-1;i++)
    {
        System.out.println(a[i]);
    }
}

}强文本

【问题讨论】:

  • a[i+1]i = a.length-1 时抛出此异常。
  • 您是否尝试过调试问题?
  • 应该是缓冲区溢出错误。
  • 有两行可以抛出此异常 a[i+1] = a[i] 和 a[loc-1] = value。

标签: java arrays exception insert


【解决方案1】:

在这部分:

for(i=a.length-1;i>loc;i--)
    {
        a[i+1]=a[i];
    }

在第一次迭代时,a[i+1] 与 a[a.length] 相同,但 数组中的最后一个元素是 a[a.length-1],因为第一个元素是 a[0],最后一个是 a[length-1],总共 a.length 个元素。所以相应地修改你的循环。

附带说明,当您定义数组的大小时,您无法更改它。大小是不可变的。所以你不能插入一个元素并尝试移动所有元素,因为你需要将大小增加1,这是不可能的。 对于这种情况,请使用ArrayList&lt;Integer&gt;&gt;ArrayList 的大小会随着您添加新元素而增加

【讨论】:

    【解决方案2】:

    正是这个for循环抛出了RuntimeException

    for(i=a.length-1;i>loc;i--) {
        a[i+1]=a[i];
    }
    

    您正在尝试设置数组的 i + 1 个元素的值,该元素不存在。

    【讨论】:

      【解决方案3】:
      /* Inserting an element in an array using its Index */
      
      
      import java.util.*;
      public class HelloWorld{
      
           public static void main(String []args){
              
              int[] a = {1,2,3,4,5};
              int[] b = new int[a.length + 1]; 
              int index = 2;
              int element = 100;
              
              System.out.println("The original array is: "+ Arrays.toString(a));
              
              // In this for loop we iterate the original array from the front
              for (int i = 0; i<index; i++){
                  b[i] = a[i];
              }
              // Here we insert the element at the desired index
              b[index] = element;
              
              // In this for loop we start iterating the original array from back.
              for (int i = a.length; i>index; i--){
                  b[i] = a[i-1];
                  // b[3] = a[2];
              }
              
              System.out.println("The new Array is: " + Arrays.toString(b));
           }
      }
      

      输出:

      原来的数组是:[1, 2, 3, 4, 5]

      新的数组是:[1, 2, 100, 3, 4, 5]

      【讨论】:

        猜你喜欢
        • 2021-11-26
        • 2020-02-21
        • 2016-12-12
        • 2020-11-11
        • 1970-01-01
        • 2013-06-01
        • 2012-04-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多