I’ve tried searching for an answer to this problem, but I’m not entirely sure what to search for. Basically what I want is for the user of my program to be able to type (into the command line):
java galaxySim HELP
and for my program to tell them some stuff about file formats and stuff. Otherwise the first argument is a filename. so the code I have to do this is:
if (args[0] == "HELP") {
System.out.printf("Help Stuff...");
}else{
filename = args[0];
System.out.printf("Filename found");
}
which is encapsulated in error handling stuff that I don’t believe affects this so haven’t written. The problem is this: whatever I type as the first argument, it ALWAYS goes to the else statement.
I’ve experimented with adding spaces before and after the argument, but it never helps. I don’t believe it to be a problem with my IF statement, as if I write
if(args[0] == args[0]){
then it does go to the correct statement. It seems as if
args[0] == "Help"
is always false. Is there perhaps some kind of encoding issue? I’m using win7, if that makes a difference.
It’s not a vital part of the program, but… It would be nice if it worked. Anyone know what’s wrong here?
Thanks!
Compare
Strings usingequalsChange this:
if(args[0] == "HELP")to
if(args[0].equals("HELP"))==compares for reference equality, not value equality. You need to check the values, hence useequals().Here’s the link for further knowledge.
You might also want to read this for understanding difference between
==andequals()method.