【问题标题】:Starting out with Java从 Java 开始
【发布时间】:2016-03-16 23:21:07
【问题描述】:

我刚开始使用 Java,我正在玩我在网上复制的代码。我在网上复制了这段代码并尝试在eclipse上运行它

http://introcs.cs.princeton.edu/java/12types/SpringSeason.java.html

public class SpringSeason { 
    public static void main(String[] args) { 
        int month = Integer.parseInt(args[0]);
        int day   = Integer.parseInt(args[1]);
        boolean isSpring =  (month == 3 && day >= 20 && day <= 31)
                         || (month == 4 && day >=  1 && day <= 30)
                         || (month == 5 && day >=  1 && day <= 31)
                         || (month == 6 && day >=  1 && day <= 20);

        System.out.println(isSpring);
    }
}

我在 Eclipse 上不断收到此错误

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 0 在 trollstartwo.main(trollstartwo.java:4)

【问题讨论】:

标签: java eclipse


【解决方案1】:

args[0]指的是字符串数组args[],它是main方法的一个参数。

.... void main(String[] args) //this args array here

args[] 数组的值由用户在运行程序时提供。在运行程序时,您可能会在 Eclipse 中看到一个用于主要方法参数的选项。您必须在此处提供 args[0]args[1] 的值。如果你不这样做,数组 args[] 甚至不会被初始化,即它仍然是一个 0 空格的数组。所以当程序试图访问 args[] 的 0 和 1 位置的值时,它甚至找不到这些位置,因此在运行时抛出 ArrayIndexOutOfBounds 异常。

为避免这种情况,请在主方法参数框中提供值。假设如果您想为月份提供“4”,为一天提供“5”,请在框中输入 {"4", "5"}

【讨论】:

    猜你喜欢
    • 2016-02-14
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2011-03-21
    • 2011-09-01
    • 1970-01-01
    相关资源
    最近更新 更多