问题描述
我有一个我不明白的小问题,希望我能得到一些帮助.我想编写一个程序,使用命令行示例(java xx 10 20)将信息添加到我的程序中.在我的程序中,我得到了类似的东西
I just have a small question which i cant understand , i hope i can get some help please .I Want to write a program that get the info into my program using the command line, example (java xx 10 20). In my program i got something like this
int coffeeCups= Integer.parseInt(args[0]);
int coffeeShots= Integer.parseInt(args[1]);
if (args.length==0)
{
System.out.print ("No arguments..");
System.exit(0);
}
else if (args.length==1)
{System.out.println("not enough arg..");
System.exit(0);
}
else if (args.length>2)
{System.out.println("too many arg.");
System.exit(0);
}
else if (Integer.parseInt(args[0]<0) && Integer.oarseInt(args[1]<0)
{system.out.println("negative chain arg");
System.exit(0); }
else if (Integer.parseInt(args[0]<0) || Integer.oarseInt(args[1]<0)
{system.out.println("negative arg");
System.exit(0);}
我只想在命令行中输入两个正整数..否则它应该拒绝我的输入,但是事情是,有时我会出现这样的错误(线程"main"中的异常java.lang.ArrayIndexOutOfBoundsException: 0),有时我的程序运行时甚至没有在COMMAND LINE中输入任何两个整数...我要尽快完成代码,感谢您的帮助P.S.不用担心我的身份,因为我的程序还没有完成
I Want to enter only TWO POSITIVE INTEGERS INTO MY COMMAND LINE.. otherwise it should reject my inputs, but the thing is that sometime i came with en error like that (Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0) and sometimes my program runs without even entering any two integers in the COMMAND LINE...I gotta finish my code as soon as possible, and i'de appreciate ur helpP.S. dont worry about the my identation as my program is not done yet
推荐答案
首先,您可能需要使用.
First of all, you may want to use a command-line-arguments parsing facility.
您正在尝试访问不存在的索引:
You're trying to access indices that do not exist:
// who said there is a first argument?
int coffeeCups = Integer.parseInt(args[0]);
// who said there is a second argument?
int coffeeShots = Integer.parseInt(args[1]);
您需要先检查,然后访问:
// this is just like using sentinel value. If you're not familiar with
// shortend `if` see notes.
int coffeeCups = args.length > 1 ? Integer.parseInt(args[0]) : null;
int coffeeShots = args.length > 2 ? Integer.parseInt(args[1]) : null;
if (coffeeCups == null || coffeeShots == null){
throw new Exception("Not enough arguments");
}
if (args.length > 2){
throw new Exception("Too many arguments");
}
在某些情况下,参数也不是Integer
.如果是这种情况,您会得到一个NumberFormatException
...
There is also the case in which the arguments are not Integer
s. You will get a NumberFormatException
if that's the case...
注释:
如果x
为true,则使用短if
表示法(x ? y : z
)返回y
,否则返回z
.
Short if
notation (x ? y : z
) is used to return y
in case x
is true, otherwise it returns z
.
这篇关于JAVA命令行参数获取信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!