+ 2

Why insert function not working

import java.util.Arrays; import java.util.Scanner; public class arrayinsert { public static void main(String[] args) { Scanner obj = new Scanner(System.in); int a[]={10,20,40,50}; System.out.println("Before inserting array elements :"+" "); for(int i=0; i<a.length;i++){ System.out.print(a[i]); } System.out.println("enter an element to insert"); int element = obj.nextInt(); System.out.println("enetr position(index) at which you want to enter"); int position = obj.nextInt(); for(int i =a.length-1;i>=position;i--){ a[i]=a[i+1]; } a[position]=element; System.out.println("operation done succcessfully"+"now printing array"); System.out.println("After inserting array elements :"); for(int i=0; i<a.length;i++){ System.out.print(a[i]); } } } I was trying this code but it is giving me error how to fix that plz help

30th Sep 2021, 4:32 AM
Viraj
Viraj - avatar
2 Respuestas
+ 2
Aleksei Radchenkov bruh i solved it i used inbuilt Array.Copyof function
30th Sep 2021, 5:50 AM
Viraj
Viraj - avatar
+ 1
Problem is that array type in java is not resizable, so if you try to add new element to it, it just goes out of bounds, causing an error, so maybe try using Vectors or some other type that you could resize. Here is how to use vectors in java: https://www.google.com/amp/s/www.jquery-az.com/java-vector-the-dynamic-arrays-explained-with-6-examples/amp/
30th Sep 2021, 5:47 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar