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.

Respuesta :

ijeggs

Answer:

  1. public class num16 {
  2.    public static void main(String[] args) {
  3.        //This code is designed to create and populate an array with
  4.        //Ten Integer values
  5.        Scanner in = new Scanner(System.in);
  6.        //Create the array
  7.        int [] intArray = new int [10];
  8.        //populating the array
  9.        for(int i =0; i<=10; i++){
  10.            System.out.print("Enter the elements: ");
  11.            intArray[i]= in.nextInt();
  12.        }
  13.        //Print the Values in the array
  14.        System.out.println(Arrays.toString(intArray));
  15.    }
  16. }

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.
ACCESS MORE