[英]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.
实际上,我在名为sum的方法中使用Varargs从用户那里获取任意数量的输入,但是我的问题是如何从用户那里获取该输入并将它们作为方法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变量参数,因此您需要先创建int数组,然后再将其传递给sum函数。
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. 记住在使用BufferedReader语句时引发Exception。 References: https://www.geeksforgeeks.org/variable-arguments-varargs-in-java/
参考: https : //www.geeksforgeeks.org/variable-arguments-varargs-in-java/
https://www.javatpoint.com/java-bufferedreader-class https://www.javatpoint.com/java-bufferedreader-class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.