Write a short program that uses a for loop to populate an array. The array can store up to 10 integers. Modify the code slightly to create a bug that would prevent the code from compiling or even better from running correctly. Be sure to describe what the code is designed to do. Monitor the post to comment when other students work to repair your code.
//This code is designed to create and populate an array with
//Ten Integer values
Scanner in = new Scanner(System.in);
//Create the array
int [] intArray = new int [10];
//populating the array
for(int i =0; i<=10; i++){
System.out.print("Enter the elements: ");
intArray[i]= in.nextInt();
}
//Print the Values in the array
System.out.println(Arrays.toString(intArray));
}
}
Explanation:
The above code looks like it will run successfully and give desired output.
But a bug has been introduced on line 9. This will lead to an exception called ArrayIndexOutOfBoundsException.
The reason for this is since the array is of length 10, creating a for loop from 0-10 will amount to 11 values, and the attempt to access index 10 for the eleventh element will be illegal
One way to fix this bug is to change the for statement to start at 1.