gpt4 book ai didi

java - 如何将用户输入的数组相乘?

转载 作者:行者123 更新时间:2023-12-01 16:39:38 25 4
gpt4 key购买 nike

我正在编写一个程序,要求用户输入数组的长度,然后询问数组的元素。我的问题是如何将这些元素相乘?例如:数组的长度是多少?: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));

关于java - 如何将用户输入的数组相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61887917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com