在数组中插入元素 - JAVA

Insert element in array - JAVA

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

class插入 {

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]);
    }
}

}强文本

就是这个for循环抛出RuntimeException

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

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

本部分:

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

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

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

/* 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]