Ressay
Ressay

Reputation: 69

Adding Items to an array in Java

I wanted to create an array that has a length specified by the user, and also wanted to have it filled by a loop command, and then it should be copied to another array by another loop command, so I wrote a code but it generates an error when trying to run it

Scanner input = new Scanner(System.in);
System.out.print("Hello, Please enter the amount of numbers: ");
int n = input.nextInt();
int array1[] = new int[n];
int array2[] = new int[n];

System.out.print("Please enter your numbers: ");

for (int i = 0; i < n; i++) {
    int index = input.nextInt();
    array1 [index] = array1 [i];
}

for (int i = 0; i < n; i++) {
    array2[i] = array2[i];
}

System.out.println("Array 1 is: " +Arrays.toString(array1));
System.out.println("Array 2 is: " +Arrays.toString(array2));

so the code runs with a single issue that all the elements are set to zero if I entered the elements of the array less than the size of the array "n". but if for example, I entered the size is 5, and tried to fill the array, the program crash if I tried to add any number larger than 5 in the array.

I know that the problem sounds silly, but I'll be grateful if you guys helped me out with it.

Upvotes: 0

Views: 469

Answers (2)

Wolfetto
Wolfetto

Reputation: 1130

You have two problems in your code.

Substitute your for(s) with the following code:

    for (int i = 0; i < n; i++) {
        int element = input.nextInt(); //elemet inserted by the user
        array1[i] = element;
    }

    for (int i = 0; i < n; i++) {
        array2[i] = array1[i];
    }

Upvotes: 1

Chouaib Seghier
Chouaib Seghier

Reputation: 71

for add item in array

 for (int i = 0; i < n; i++) {
        int index = input.nextInt();
        array1 [i] = index ;
    }

Upvotes: 1

Related Questions