3

How do I print out a set of integers from my args variable in Java?

I tried:

System.out.println("The numbers are " + args.length);

But all that does is print out the number of elements in the array.

I want it so that if there are 5 arguments passed: 1 2 3 4 5 the output should be:

1, 2, 3, 4, 5
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
syncoroll
  • 137
  • 2
  • 3
  • 10

3 Answers3

12

Take a look if you like

  System.out.println("The numbers are "+Arrays.toString(args));

If not, you'll have to loop over the array and format it yourself.

Thilo
  • 257,207
  • 101
  • 511
  • 656
2

But all that does is print out the numbers in the array not the numbers separately.

This seems to be somewhat unclear.

args.length gives the length of the array rather than its elements.

Use a for loop:

System.out.println("The numbers are ");

for(int i=0; i < args.length; i++)
    System.out.print(args[i] + " ");
Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Shraddha
  • 2,337
  • 1
  • 16
  • 14
  • The compiler gives me an error of "i cannot be resolved to a variable" When i resolve it with "int b = 0;" it gives me a single integer, rather than the integers in args. – syncoroll Aug 10 '11 at 11:17
2

Try:

for(String arg: args)
    System.out.print(arg + " ");
Marcelo
  • 11,218
  • 1
  • 37
  • 51