Java数组索引超出范围的esception [英] Java arrays index out of bounds esception
问题描述
应该创建名称由数组名称指定的文件的代码,但错误是
线程中的esceptionmainjava.lang.ArrayIndexOutOfBoundsException:5
in inout.ArrayWriteFiles.main(ArrayWriteFiles.java:30)
public class ArrayWriteFiles
{
public static void main(String [] args)throws IOException
{
String [] Names = new String [5];
姓名[0] =Android;
Names [1] =java;
Names [2] =computerscience;
姓名[3] =卫星;
姓名[4] =沟通;
for(int i = 0; i< = Names.length; i ++){
String fileName =name+ Names [i] +。html;
PrintWriter printer = new PrintWriter(fileName,UTF-8);
printer.write(Java是面向对象的);
printer.close();
}
}
}
我尝试了什么:
更改了代码并搜索了java类
for循环中的条件是
i< = Names.length;
这里Names.length在你尝试访问的最后一次迭代中计算结果为5数组索引为5的元素,对于长度为5的数组是不可能的。
尝试将条件更改为
我< Names.length;
GKP1992 已经给你正确答案了。
但请注意,你也可以用这种方式编写循环(参见 for Statement - Java教程 - 学习Java语言 - 语言基础知识 [ ^ ])
for ( String 名称:名称)
{
字符串 fileName = name + name + 。html;
// ...
}
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
The condition in your for loop is
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
i < Names.length;
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 [^])
for(String name : Names) { String fileName = "name" + name + ".html"; //... }
这篇关于Java数组索引超出范围的esception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!