英文:
How to mulitply the user entered arrays?
问题
我正在制作一个程序,要求用户输入数组的长度,然后询问数组的元素。我的问题是如何将这些元素相乘?例如:
数组的长度是多少?:4
数组的元素是什么?:3 6 4 7
{3 6 4 7} 的乘积为 504。
以下是我的代码:
import java.util.Scanner;
import java.util.Arrays;
public class ArrayMultiplication {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输入数组的长度:");
int length = s.nextInt();
int[] myArray = new int[length];
System.out.println("请输入数组的元素:");
for (int i = 0; i < length; i++) {
myArray[i] = s.nextInt();
}
int product = 1;
for (int num : myArray) {
product *= num;
}
System.out.printf("{%s} 的乘积是 %d。", Arrays.toString(myArray), product);
}
}
英文:
im making a program the asks the user to enter the length of the array, and then asks the elements of the array. My question is how do i mulitply these elements? for example:
What is the length of the array?: 4
What are the elements of the array?: 3 6 4 7
the multiplication of {3 6 4 7} is 504.
here is my code so far:
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));
}
}
Any help would be appreciated.
答案1
得分: 0
Scanner s = new Scanner(System.in);
System.out.println("您的数组长度是:");
int length = s.nextInt();
System.out.println("您的数组元素是:");
long product = 1;
for (int i = 0; i < length; i++) {
product *= s.nextInt();
}
System.out.printf("数组元素的乘积为:%d", product);
// 使用稍微调整的代码更新了您的代码
// 替代方法使用 Lambda 表达式:
Scanner s = new Scanner(System.in);
List<Integer> numbers = new ArrayList();
System.out.println("您的数组长度是:");
int length = s.nextInt();
System.out.println("您的数组元素是:");
numbers = IntStream.range(0, length)
.mapToObj(i -> Integer.valueOf(s.nextInt()))
.collect(Collectors.toList());
System.out.printf("数组元素的乘积为:%s", numbers,
numbers.parallelStream()
.reduce(1,
(number, product) -> product * number));
英文:
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);
updated your code with a slight tweak
Alternate using 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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论