如何乘以用户输入的数组?
How to mulitply the user entered arrays?
我正在制作一个程序,要求用户输入数组的长度,然后询问数组的元素。我的问题是如何将这些元素组合在一起?例如:
数组的长度是多少?:4
数组的元素是什么?: 3 6 4 7
{3 6 4 7} 的乘法是 504。
到目前为止,这是我的代码:
Scanner s = new Scanner(System.in);
System.out.println("The length of your array is: ");
int length = s.nextInt();
int [] myArray = new int [length];
System.out.println("The elements of your array are: ");
for(int i=0; i<length; i++ ) {
myArray[i] = s.nextInt();
}
System.out.printf("The multiplication of {%s} is ",Arrays.toString(myArray));
}
}
如有任何帮助,我们将不胜感激。
Scanner s = new Scanner(System.in);
System.out.println("The length of your array is: ");
int length = s.nextInt();
System.out.println("The elements of your array are: ");
long product = 1;
for (int i = 0; i < length; i++) {
product *= s.nextInt();
}
System.out.printf("The multiplication of {%s} is ", product);
稍作调整更新了您的代码
交替使用 lambda:
Scanner s = new Scanner(System.in);
List<Integer> numbers = new ArrayList();
System.out.println("The length of your array is: ");
int length = s.nextInt();
System.out.println("The elements of your array are: ");
numbers = IntStream.range(0, length)
.mapToObj(i -> Integer.valueOf(s.nextInt()))
.collect(Collectors.toList());
System.out.printf("The multiplication of {%s} is {%s}",numbers,
numbers.parallelStream()
.reduce(1,
(number, product) -> product * number));
我正在制作一个程序,要求用户输入数组的长度,然后询问数组的元素。我的问题是如何将这些元素组合在一起?例如: 数组的长度是多少?:4 数组的元素是什么?: 3 6 4 7 {3 6 4 7} 的乘法是 504。 到目前为止,这是我的代码:
Scanner s = new Scanner(System.in);
System.out.println("The length of your array is: ");
int length = s.nextInt();
int [] myArray = new int [length];
System.out.println("The elements of your array are: ");
for(int i=0; i<length; i++ ) {
myArray[i] = s.nextInt();
}
System.out.printf("The multiplication of {%s} is ",Arrays.toString(myArray));
}
}
如有任何帮助,我们将不胜感激。
Scanner s = new Scanner(System.in);
System.out.println("The length of your array is: ");
int length = s.nextInt();
System.out.println("The elements of your array are: ");
long product = 1;
for (int i = 0; i < length; i++) {
product *= s.nextInt();
}
System.out.printf("The multiplication of {%s} is ", product);
稍作调整更新了您的代码
交替使用 lambda:
Scanner s = new Scanner(System.in);
List<Integer> numbers = new ArrayList();
System.out.println("The length of your array is: ");
int length = s.nextInt();
System.out.println("The elements of your array are: ");
numbers = IntStream.range(0, length)
.mapToObj(i -> Integer.valueOf(s.nextInt()))
.collect(Collectors.toList());
System.out.printf("The multiplication of {%s} is {%s}",numbers,
numbers.parallelStream()
.reduce(1,
(number, product) -> product * number));