0

How can I create a a variable length argument using only user input? I want the user to be able to enter in 2 different kinds of data by themselves. How can I do this? I have this part down and understood, but I'm unsure of how I can change it so that the user input's it from the command line. This was a sample code I found from online. I haven't modified my code yet, but this is all I know how to do.

public static void main(String [] args){
System.out.println(average(43,546,76,8));
}

public static int average(int ... numbers){

    int total = 0; 
    for(int x: numbers); 
    total =+x; 
    return total/numbers.length; 
}
johnny 5
  • 19,893
  • 50
  • 121
  • 195
  • 1
    It's not very clear what you are asking here, but generally your main will take standard in as a bunch of Strings, and you will massage and validate those Strings based on your requirements. If there is a problem with the data exit with a message, otherwise, pass the massaged data onto the appropriate methods, and handle the results for display or reporting. In this case, if you want to get integers from the command line, you will have to validate and massage a String like "43" into an int value of 43, and pass it and it's friends into the appropriate method. –  May 31 '18 at 15:20
  • Break the problem down into pieces: how do you grab and parse command line args? What do those args look like? How do you turn those into the data you need? Give that a try and come back when you have specific questions. Starting point: https://stackoverflow.com/q/5585779/1531971 –  May 31 '18 at 15:22

2 Answers2

1

Say if I have the main method that prints all the command line arguments.

 public static void main(String[] args)
  {
    for(int i=0;i< args.length;i++)
    {
    System.out.println(args[i]);
    }
  }

This will print 43 546 76 8 when I execute the compiled class that has the main method , and pass the arguments from command line as:

java mainClass 43 546 76 8

So you can use args array to pass the input to your method the way you need.

JineshEP
  • 738
  • 4
  • 7
0

Command line arguments will be passed to the args parameter in your main method. Use Integer.parseInt() to convert it to an int. If you want to get the user input during runtime have a look at the Scanner class.

Bene
  • 724
  • 8
  • 20