[英]Is it possible to pass input.next - after verification - directly to a method as parameters in a variable length argument list? <in java>
package compute.greatest.common.denominator;
import java.util.Scanner;
public class computeGreatestCommonDenominator{
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
final int MAX = 20;
final int MIN = 2;
System.out.println("Enter between " + MIN + " and " + MAX + " numbers ( inclusive ) to find the GCD of: ");
for(int i = 0; input.nextInt() != '\n'; i++) { // Normally I would use a for loop to populate input into
if(input.nextInt() < MIN) { // an array and pass the array to method gcd().
System.out.println("ERROR! That number is not within the given constraints! Exiting.......");
System.exit(1); // Any non-zero value, is considered an abnormal exit.
}
}
public static int gcd(int... numbers) {
int greatestCommonDenominator = 0;
}
}
Normally I would use a for loop to populate input into an array and pass that to method gcd(int... numbers). 通常,我将使用for循环将输入填充到数组中并将其传递给方法gcd(int ... numbers)。 However, that seems to be a case of redundancy to me - passing an array to a variable length argument list, which is treated as an array.
但是,这对我来说似乎是多余的情况-将数组传递给可变长度参数列表,该列表被视为数组。 First let me say that I'm still in the learning phase of java and, while understanding variable length argument lists, it's not a confident understanding.
首先,我要说的是我仍处于Java的学习阶段,尽管理解可变长度参数列表,但这并不是一种自信的理解。 Is there a way to verify the input data and pass it, one by one, in the loop, directly to the variable length argument list - without using an array?
有没有一种方法可以验证输入数据并在循环中将其一个接一个地直接传递给可变长度参数列表-无需使用数组? With an array seems redundant to me and without seems illogical :/
数组似乎对我来说是多余的,而且似乎也不合逻辑:/
I think you are misunderstanding the use of variable length parameters (varargs) here. 我认为您在这里误解了可变长度参数(varargs)的使用。
Varargs are nice syntactic sugar because it makes this code: Varargs是不错的语法糖,因为它可以编写以下代码:
int[] ints = {1, 2, 3};
gcd(ints);
more elegant: 更优雅:
gcd(1, 2, 3);
That is the purpose of varargs. 这就是varargs的目的。
If you don't have or expect code like this: 如果您没有或期望这样的代码:
int[] ints = {1, 2, 3};
gcd(ints);
then varargs is not so useful, and certainly don't force your code fit into this varargs thing. 那么varargs并不是那么有用,当然不要强迫您的代码适合varargs。
My suggestion is that you keep your code the way it is, or you can change the varargs into a normal array parameter if you don't need to use the varargs feature anywhere else in your code. 我的建议是按原样保留代码,如果不需要在代码的其他任何地方使用varargs功能,则可以将varargs更改为常规数组参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.