Member Avatar for BobTheLob

Hey, I have a potentially very stupid question. I'm working on a project where I need to input a few numbers. What I would like to do is run it via the command line like, "java test 2 3", where 2 and 3 would be the inputs. I want to do this instead of running the program and then typing the two numbers in.
I have in my class:

import java.io.*;
import java.util.Scanner;

public class test {

        public static void main(String[] args) throws IOException{
                Scanner input = new Scanner(System.in);
                int a = input.nextInt();
                int b = input.nextInt();

                System.out.print(a+b);
        }

}

Note, i'm working on a larger project, but i couldn't get this one feature to work, so i created a quick test class to figure this bugger out.
How would I go about doing this?

That is exactly what your args parameter to the main method is for.

In the example you mentioned,"java test 2 3", args would include {2,3}.

You can simply access them by index.

int a = args[0];
Member Avatar for BobTheLob

That is exactly what your args parameter to the main method is for.

In the example you mentioned,"java test 2 3", args would include {2,3}.

You can simply access them by index.

int a = args[0];

Beautiful. Although I did have to cast the args into an int for that to work, I got the desired result. Thanks!

Yeah, sorry for that. In my typing haste I totally ignored the different types.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.