0

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.

4
  • 7
    array1 [index] = array1 [i]; should be changed to array1 [i] = index; Btw, your second loop makes no sense, did you mean array2[i] = array1[i];? Commented Oct 31, 2019 at 8:35
  • 2
    and change the variable name from index to number or data or element or such. Otherwise it is very confusing. Commented Oct 31, 2019 at 8:36
  • Arrays index always start from 0 and in you case size of array is 5 you index values are 0, 1, 2, 3 4 if you enter index 5 it is going out of index range. Commented Oct 31, 2019 at 8:39
  • @JoakimDanielson, yes I meant array2[i] = array1[i]; thank you for that bro. Commented Oct 31, 2019 at 9:01

2 Answers 2

1

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];
    }
Sign up to request clarification or add additional context in comments.

Comments

1

for add item in array

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.