中易网

java中使用命令行参数获得数据,按照题目要求,当运行时,不加参数时,应该是输出提示信息“erro

答案:3  悬赏:80  
解决时间 2021-04-27 22:19
  • 提问者网友:斩断情丝
  • 2021-04-27 19:21
java中使用命令行参数获得数据,按照题目要求,当运行时,不加参数时,应该是输出提示信息“error”,但是我这么运行,却显示异常,哪里出了问题。应该怎么改?
最佳答案
  • 二级知识专家网友:安稳不如野
  • 2021-04-27 20:13
因为你没有在命令中传入参数,所以现在args这个数组是空的。但是当你用
if (args[0] == null)比较时,你试图访问args数组中的第一项args[0],而现在数组还是空的,并没有args[0](不是null而是根本不存在),这样就会产生ArrayIndexOutOfBoundsException。你可以把if语句修改成如下以解决该问题:
if (args.length == 0)   // 数组长度为零就意味着这个数组是空的,也就是没有参数
    System.out.println("Error."); 或者一定要用args[0]也可以使用try catch语句:
public class E13q3 {
    public static void main(String[] args) {
        try {
        if (args[0] == null)
        System.out.println("Error.");
    } catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Error.");
    }
    }
}
全部回答
  • 1楼网友:woshuo
  • 2021-04-27 21:19
if the program is called as java message -g cruel world then the args array has the following contents: args[0]: "-g" args[1]: "cruel" args[2]: "world" the program prints the message goodbye, cruel world!
  • 2楼网友:厌今念往
  • 2021-04-27 20:20
public class E13q3 { public static void main(String[] args) { if(args==null){//数组下标越界了 System.out.println("error"); } } }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息