+ 2
How can I insert numbers in a certain position in arrays in Java?
Actually, I'm running a loop in which I want to insert the input taken in the array in the sequence of input. But I'm not able to understand how to perform that action... Here's the code: System.out.print("Input the range: "); int n1=sc.nextInt(),n2,x=0; for(int i=0;i<n1;i++) { n2=sc.nextInt(); int arr[x++]=arr[n2]; } The error is in the last line and it's a run time error java.lang.ArrayIndexOutOfBoundsException:18
5 Réponses
+ 3
// full code is
import java.util.Scanner;
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Scanner sc = new Scanner("5\n2\n4\n6\n8\n10"); // test
System.out.print("Input the range: ");
int n1 = sc.nextInt(), n2, x=0;
int[] arr = new int[n1]; //declare array here
for(int i=0; i<n1; i++) {
n2 = sc.nextInt();
arr[x++] = n2; //orig: int arr[x++] = arr[n2];
}
System.out.println( "\n"+Arrays.toString(arr) );
}
}
// +Denise has also done some optimizations
+ 2
Hello Utkarsh, there are some points I noticed from the snippet, is that the whole code? cause I don't see where the array <arr> was declared.
I don't get how you want the array will be, so let's assume we have this array:
{1,2,3,4,5}
And we input five values:
2 4 1 3 0
How the array looks after the loop complete?
+ 2
You don't need x. You can just use i from your for loop.
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] arr = new int[n];
Now you have an array with length = n which you can fill using a for loop:
for(int i = 0; i < n; i++){
arr[i] = scan.nextInt();
}
+ 1
Sorry! I will make some corrections and hope you will help me.
Thanks
+ 1
Can you upload your code in code playground, link it here and tell us the specific spot?