嗨,我正在尝试学习数组,我们的老师给了我们一个额外的作业,上面写着:“用一年中的每个月(一月,二月......)创建一个数组。我的代码如下所示:
package array2;
public class Array2 {
static String months[];
public static void main(String[] args) {
months = new String[13];
months[0] = null ;
months[1] = "January";
months[2] = "February";
months[3] = "March";
months[4] = "April";
months[5] = "May";
months[6] = "June";
months[7] = "July";
months[8] = "August";
months[9] = "September";
months[10] = "October";
months[11] = "November";
months[12] = "December";
int m = Integer.parseInt( args[0] );
System.out.println( months[ m ] );
}
}
但我收到错误
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at array2.Array2.main(Array2.java:33)
/Users/Mo/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
有人可以帮忙澄清一下吗?
最佳答案
错误出现在三个地方:
在你的程序中。您需要确保 args 不是空数组(确保用户确实提供了至少 1 个参数)。
以您调用程序的方式。您很可能没有传递任何参数。如果您从命令行运行程序,可以按以下方式执行:
java array2.Array2 5
应打印“May”。
确保从参数中解析的 int 在范围内。
if(args.length == 0) { System.out.println("Error, must specify one argument"); } else { int m = Integer.parseInt( args[0] ); if(m<0 || m> 12) { System.out.println("Invalid month specified"); } else { System.out.println( months[ m ] ); } }
关于java - 数组 - 输出必须是一年中的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42282660/