Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
code that should create files with names as specified by array Names, however the error is

"Esception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at inout.ArrayWriteFiles.main(ArrayWriteFiles.java:30)"

public class ArrayWriteFiles 
{      

public static void main(String[] args) throws IOException
{         
        String[] Names = new String[5]; 
        Names[0] = "Android";
        Names[1] = "java";
        Names[2] = "computerscience";
        Names[3] = "satellite";
        Names[4] = "communication";        
  for(int i=0 ; i<=Names.length ; i++){
  String fileName = "name" + Names[i] + ".html";
  PrintWriter printer = new PrintWriter(fileName, "UTF-8");   
  printer.write("Java is object oriented"); 			
  printer.close();
  }
}
} 


What I have tried:

changed code and searched java classes
Posted
Updated 7-May-18 0:39am

The condition in your for loop is
JavaScript
i<=Names.length;

Here Names.length evaluates to 5 to for the last iteration you try to access the element at array index 5 which is not possible for an array of length 5.

Try changing the condition to
JavaScript
i < Names.length;
 
Share this answer
 
v2
Comments
CPallini 7-May-18 6:34am    
5.
GKP1992 7-May-18 6:38am    
TY.
four systems 8-May-18 6:58am    
wow, the esception is gone but the code did not create any files,
GKP1992 already gave you the correct answer.
However, please note, you may also write the loop this way (see The for Statement - The Java Tutorials - Learning the Java Language - Language Basics [^])
Java
for(String name : Names)
{
  String fileName = "name" + name + ".html";
  //...
}
 
Share this answer
 
Comments
four systems 9-May-18 7:39am    
wonderful, another way for file creation
four systems 9-May-18 7:40am    
ty

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900