Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Command Line Arguments in Java  RSS feed

 
naomi newman
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I write a program that passes an unspecified number of integers as command-line arguments to the main method and display their total?

This is what I have



Am I missing a method? Any help would be great!
 
Junilu Lacar
Sheriff
Posts: 11144
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't have to split them. Just separate the numbers by spaces on the command line. For example:


Will run SumUp.main with args having 7 elements, one element for each number given on the command line. You'd just need to parse each one to turn it into an int, but you're already doing that. Basically you can eliminate line 3 in your main method and use the args array directly in your for-loop.

BTW, please format / indent your code properly. Improperly indented code is difficult to read and it will confuse you and others. Here's your code properly formatted/indented:

Notice the use of spaces and blank lines to separate parts of your program so that it's easier to distinguish them from each other.

There are a number of Java Style Guides readily available on the Internet, pick a style and follow it consistently.>
 
naomi newman
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
Campbell Ritchie
Marshal
Posts: 55715
163
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now Java8 is here, the challange is how to do that without using the keywords for and while.
You can create a Stream which iterates an array with a method of the Arrays class; since args is a String[], the Stream will be of type String. You can convert that to an IntStream with the mapToInt method using Integer.parseInt and then the IntStream interface has a sum() method:-Note you usually format Stream code so the dots are all aligned vertically. If you pass "five" rather than "5" as an element, you will suffer a number format exception. You have to run the code like this:-
java ArrayAdder 1 2 3 10 11 7 15
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!