2

I have a method:

public String sample (String A, int B, int C){
     String fin = "";
     if(C==0){
     fin="fail";
     }
     return fin;
}

I want to run it in command line like this: d:>java -jar prac.jar B=5 How can I set parameter in command line with "="?

zsocc
  • 23
  • 3
  • Why not use thirdparty java CLI parser like [Apache Commons CLI](http://commons.apache.org/proper/commons-cli/)? Nearly complete list of available CLI parser could be found [here](http://stackoverflow.com/questions/367706/how-to-parse-command-line-arguments-in-java/3337023#3337023). – luka5z May 03 '16 at 22:15

2 Answers2

0

In your main method, you deal with parameters that are passed:

public static void main(String[] args) {
    // args[0] = parameter 1;
    // args[1] = parameter 2;
    // args[n] = parameter n+1;
    sample(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2])); 
}
Rabbit Guy
  • 1,840
  • 3
  • 18
  • 28
  • 1
    You forgot `new`. Or better yet, `Integer.parseInt()`. – shmosel May 03 '16 at 16:21
  • and how can I set parameter IN command line? Like i wrote, d:>java -jar prac.jar B=5 – zsocc May 03 '16 at 16:26
  • @zsocc Meaningless question. Your `sample` method takes 3 parameters, so only passing one is not enough. – Andreas May 03 '16 at 16:30
  • That's my problem, if I dont set value for parameter it will get a default value, (or it should) – zsocc May 03 '16 at 16:34
  • No, you are wrong. If you do what I did in this main method, which is how you use parameters, you assign values to specific variables based on their location in your arguments. If you ran `d:> java -jar prac.jar 5` then the first argument passed to the sample method will be equal to 5. – Rabbit Guy May 03 '16 at 16:36
  • Okey Thank You I figured it out how should I write this. :) and yes U forgot Integer.parseInt() :) – zsocc May 03 '16 at 16:43
  • Updated using `Integer.parseInt()` – Rabbit Guy May 03 '16 at 17:56
0

you need to do in the main something like parsing the args to integer:

use Integer.parseInt()... and validate the input is a numeric parsable value...

public static void main(String[] args) {
    System.out.println(sample(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2])));
}

public static String sample(String A, int B, int C) {
    String fin = "";
    if (C == 0) {
        fin = "fail";
    }
    return fin;
}

and to run it from the cmd

java StringA n1 n2

Example:

enter image description here

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97