0

Need some assistance with this program. Don't know what I need to do.

import java.io.*;               // Needed to open and modify binary data


public class FileEncryptionFilter

  {
  public static void main(String [] args)
                                throws IOException
  { 
     // An array to write the file
      int[] numbers = { 2, 4, 6, 8, 10, 12, 14 };

      // Create the binary output objects
      FileOutputStream fstream =
                    new FileOutputStream( "Numbers.dat");
      DataOutputStream outputFile =
                    new DataOutputStream( fstream);

      System.out.println( "Writing the numbers to the file...");

      // Write the array elements to the file  
      for (int i = 0; i < numbers.length; i++)
            outputFile.writeInt(numbers[i+10]);

      System.out.println( "Done.");

      System.out.println( "Encrypting.....");
      outputFile.writeInt(numbers);

      System.out.println( "Done.");

      // Close the file
      outputFile.close();
    }
}   





run:
Writing the numbers to the file...
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at FileEncryptionFilter.main(FileEncryptionFilter.java:23)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
2
Contributors
2
Replies
14
Views
4 Years
Discussion Span
Last Post by richard.haines.39
0

You're getting an ArrayIndexOutOfBoundsException because you are trying to access indexes that are not valid in your array.
The array you are iterating over is smaller than 10 elements, yet you are adding 10 to every i, which is guaranteed to be out of bounds for any i >= 0.

Instead of: numbers[i+10] you probably intended: numbers[i].

Edited by mvmalderen

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.