我正在做一个程序,要求用户输入数组的长度,然后询问数组的元素。例如:数组的长度是多少?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);
更新了你的代码,稍作调整
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));