command line arguments in java

  • Thread starter Thread starter GeX
  • Start date Start date

GeX

GeX

Soldato
Joined
17 Dec 2002
Posts
6,981
Location
Manchester
i'm a bit rusty with java, what i want to do is from the CLI, launch the app and using an argument (add/remove) add two strings into an array.

i've not given any thought to the array side of things as i know what im doing there, what im not sure is how to handle the arguments.

Code:
public class Echo {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}

i know that that will echo any arg i pass it, but if i say gave it "echo hello you smell", it would treat each arg as a new string, and echo it on a new line. What i don't know is how to take each string and copy it into a string within my code.

Am i making sense here?
 
Well at the moment when you run your program with the specified arguments you are creating an array that is being passed to the main method:

Code:
String[] args = { "echo", "hello", "you", "smell" }

So if you want to access each item individually then you could do something like:
Code:
String arg1 = args[0];
String arg2 = args[1];
String arg3 = args[2];
String arg4 = args[3];

System.out.prinln(arg1+" "+arg2);
System.out.prinln(arg3+" "+arg4);

//Output
echo hello
you smell
This would create an initialise 4 String variables which each contain the different arguments you passed in. If you want to treat it as a whole string then you could do this (similar to your example):
Code:
StringBuilder sb = new StringBuilder();
for (String s : args) {
	sb.append(s+" ");
}
String allArgs = sb.toString();
System.out.println(allArgs);

//Output
echo hello you smell

I am confused with what you are trying to do with the arguments but hopefully this helps. Feel free to post more code if you get stuck with anything.
 
JRE needs to be 5.0 for the for(args) to work. For the string builder, you can do
Code:
String s = "";
for(i = 0; i++ < args[].length; i++)
{
s = s + args[i];
}
 
Last edited:
The StringBuilder is way more efficient than string concatenation, it probably doesn't matter for a small program but I've got into the habbit of using it once I saw the performance increase it offers. There aren't too many reasons to be coding to an old JVM because the newever versions have several performance tweaks which it can pay to make use of. I assume he is using Java 5 or above because he used the enhanced-for loop in his code.
 
yeah, fair enough. I think the op's having trouble getting the strings from the main method to the array, but doesn't give the location of the array.
 
Back
Top Bottom