Java main 方法参数处理,取决于用户输入
我想知道如何比较传递给 java main 方法的参数。
eg java hello -i
我尝试打印 args[0] ,它确实给了我 -i 。但是我想要实现的是:
if args.length == 0 {
do something
}
else if args[0] =="-i"{
do something
}
但是我不断收到索引越界异常。无论如何,是否可以将字符串数组 args 中的字符串转换为字符串类型,以便我可以比较它?
public static void main(String[] args) {
if args.length == 0 {
do something
}
else if args[0] =="-i"
do something
}
}
例如,如果他们在没有任何参数的情况下启动程序,我将调用 init() 方法。但如果他们输入 -i 作为参数,我将调用 install() 。
I would like to know to know how do i compare the arguments passed into a java main method.
eg java hello -i
I tried printing args[0] and it does indeed gives me -i. however what i want to achieve is:
if args.length == 0 {
do something
}
else if args[0] =="-i"{
do something
}
However i keep getting index out of bound exception. is there anyway to convert the string in the string array args to just a string type so i can compare it?
public static void main(String[] args) {
if args.length == 0 {
do something
}
else if args[0] =="-i"
do something
}
}
for example if they start the program without any arguments, i will call init() method. but if they entered -i as arguments, i will call install() instead..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您给出的代码甚至无法编译,但这确实可以工作:
请注意,在这里使用
else
很重要 - 这会失败,例如:此时,即使数组的长度为 0,您也会检查
args[0]
。鉴于您目前给出了伪代码(条件周围没有括号),我想知道这是否是您真实代码中的问题。(另请注意使用
equals
而不是==
,正如其他人已经指出的那样。)The code you've given wouldn't even compile, but this does work:
Note that it's important that you're using
else
here - this would fail, for example:at that point you're checking
args[0]
even if the length of the array is 0. Given that you've given pseudo-code at the moment (no brackets round the conditions) I wonder whether that's the problem in your real code.(Also note the use of
equals
instead of==
as others have already pointed out.)比较字符串时,您需要使用 equals() 方法,因为 == 比较它们是否是相同的字符串(与相等不同)。
这是一个示例,
尝试在不带参数、第一个参数或任何其他参数的情况下调用它。
When comparing strings you need to use the equals() method as the == compare if they are the same string (not same as if they are equal).
Here's an example
Try calling it with no arguments, the argument first or any other arguments.
你不需要转换它。但是,您确实需要以正确的方式进行比较;例如
(如果您使用
==
来比较字符串,您可能会遇到麻烦。==
运算符测试两个引用是否指向同一个对象。什么您实际上需要的是查看两个字符串是否包含相同的字符...并且您需要使用equals
方法来执行此操作。)但是,这并不能解释为什么您会得到
IndexOutOfBoundsException
。我需要查看真实代码来回答这个问题。You don't need to convert it. However, you do need to compare it the right way; e.g.
(If you use
==
to compare strings, you are likely to get into trouble. The==
operator tests to see if two references point to the same object. What you actually need is to see if two strings contain the same characters ... and you need to use theequals
method to do that.)However, this doesn't explain why you were getting
IndexOutOfBoundsException
. I'd need to see real code to answer that.