Reputation: 12269
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..
Upvotes: 0
Views: 4097
Reputation: 718826
Is there anyway to convert the string in the string array args to just a string type so I can compare it?
You don't need to convert it. However, you do need to compare it the right way; e.g.
if (args.length == 0) {
// do something
} else if (args[0].equals("-i")) {
// do something else
}
(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 the equals
method to do that.)
However, this doesn't explain why you were getting IndexOutOfBoundsException
. I'd need to see real code to answer that.
Upvotes: 0
Reputation: 11543
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
public static void main(String[] args) {
if (args.length == 0) {
System.err.println("No arguments");
} else if (args.length == 1) {
if (args[0].equals("first")) {
System.err.println("The argument equals 'first'");
} else {
System.err.println("Don't know what you want with " + args[0]);
}
} else {
System.err.println("Will not use the arguments");
for (String arg: args) {
System.err.println(arg);
}
}
}
Try calling it with no arguments, the argument first or any other arguments.
Upvotes: 0
Reputation: 1500675
The code you've given wouldn't even compile, but this does work:
public class Test {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No arguments!");
} else if (args[0].equals("-i")) {
System.out.println("-i passed");
} else {
System.out.println("Something else");
}
}
}
Note that it's important that you're using else
here - this would fail, for example:
if (args.length == 0) {
System.out.println("No arguments!");
}
if (args[0].equals("-i")) {
System.out.println("-i passed");
}
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.)
Upvotes: 3