简体   繁体   中英

How to take any number of arguments from the user and pass them to a method which uses varargs( variable argument )?

I want to take any number of input from the user, and then do their summation as a final product. Infact I am using Varargs in method called sum to take any number of input from the user, but my problem is to how to take that input from the user and pass them as the argument for the method sum.

public class calculator 
{
   public static void main(String args[])
   {
      BasicFunc obj = new BasicFunc();
      int result = obj.sum(); // here i want user to input any number of 
                              // arguments.
      System.out.println(result);
   }
}

class BasicFunc
{   
   int sum(int...x) // i have used here varargs
   {
        sum = 0;
        for(int a=0 ; a<x.length ; a++) sum += x[a];
   }
   return sum;
}

You can use:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] nums = br.readLine().split(" "); //delimitation by space or comma

Since you are using int variable arguments you need to create int array before passing it to sum function.

int[] numbers = new int[nums.length];
for(int i = 0;i < nums.length;i++){
   numbers[i] = Integer.parseInt(nums[i]);
}
BasicFunc obj = new BasicFunc();
int result = obj.sum(numbers);

Remeber to throw Exception while using BufferedReader statement. References: https://www.geeksforgeeks.org/variable-arguments-varargs-in-java/
https://www.javatpoint.com/java-bufferedreader-class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM