简体   繁体   中英

Trying to pass arguments to java application

So I have a program with an updater and I've made a mistake before releasing it. I totally forgot about by-passing the update so the user can update it later.

Now I'm trying to fix it and I thought that creating an argument with "-no_patching" is the best solution to this.

Here's the code:

public static void main(String... args) throws Exception {
    if (args.length == 0) {
        checkVersion();
        System.err.println("patching ON");
    } else if(args.toString().matches("-no_patching")) {
        System.err.println("patching OFF");
        launchApp();
    }
}

The thing is when i run the program with argument it runs for 1 second then it stops. What I'm doing wrong ?

Here is the mistake at line args.toString().matches("-no_patching") .

That should be

else if(args[0].equals("-no_patching")){ // make sure args length is 1
            System.err.println("patching OFF");
            launchApp();
        }

toString() on args array wont give you contents.

You are trying to match the args array instead of matching first argument from that array.

//this is not what you want
args.toString().matches("-no_patching") 

You need to get first element from array and then do comparison :

args[0].equals("-no_patching")

args is array. You should do it like this:

for(String arg : args)
{
    if(arg.matches("-no_patching")){
        System.err.println("patching OFF");
        launchApp();
    }
}

Try this, convert args to a List and use the contains method to see if there are any argument matches:

public static void main(String... args) throws Exception {
    if(args.length == 0){
    checkVersion();
    System.err.println("patching ON");
    } else if(Arrays.asList(args).contains("-no_patching")){
        System.err.println("patching OFF");
        launchApp();
    }
}

i totally forgot about array thing... i guess I panicked a bit xD

else if(args[0].equals("-no_patching")){
   //do something
}

did the trick, Thank you!

I think you are trying an incorrect comparison in the ELSE IF

         else if(args.toString().matches("-no_patching"))

args.toString() would give some address value of the argument array args. If this is compared with your "-no_patching" argument it would definitely return FALSE.

Rather you can always compare like

         else if(args[0].toString().matches("-no_patching"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM