java - 如何乘以用户输入的数组?
问题描述
我正在制作一个程序,要求用户输入数组的长度,然后询问数组的元素。我的问题是如何将这些元素相乘?例如:数组的长度是多少?: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));
推荐阅读
- c# - Google api OAuth 因重定向 uri 不匹配而失败
- javascript - AWS Cognito 和 Amplify:刷新会话时未发送 clientMetadata
- python - 如何替换字符串中第 N 次出现的单词?
- c - 有人可以解释一下为什么 C 中的 #include 指令允许包含“.h”文件以外的文件
- java - 验证涉及 LinkedList 的 3 个循环的 Big-O
- object - 我们如何在JS中提取2个对象的相交键及其相交值?
- excel - 我在 vba 中使用 AutoFilter 时遇到问题。出现错误 -2147417848 (80010108)
- docker - 组合后在docker容器中执行命令
- vscode-settings - Prettier 禁用某些语言不起作用
- c# - .net 核心解码的 JWT 声明类型与生成时使用的声明类型不匹配