[英]How to sum elements of an ArrayList which are values of a HashMap using java streams?
[英]Java to insert the input values into ArrayList and print sum of elements present at even index of the ArrayList using Iterator
我已经写了这段代码我的问题是它的长度。 数组作为输入但不读取数组的元素我们必须使用迭代器来读取所有输入。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.*;
public class arrayl {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList < Integer > list = new ArrayList < Integer > ();
System.out.println(" Enter the length of array :");
int n = sc.nextInt();
int array[] = new int[n];
System.out.println("Enter List : ");
for (Iterator < Integer > itr = list.iterator(); itr.hasNext();) {
if (itr.next() != null) {
while (itr.hasNext()) {
Integer thisInt = itr.next();
if (thisInt % 2 == 0) {
list.add(thisInt);
}
System.out.println(" Even Index Position Sum : ");
}
}
}
}
}
您尚未向ArrayList
添加任何内容,因此您的for
循环不会执行任何操作。 您必须首先使用list.add(element)
向其中添加一些内容,其中element
是int
。
根据您询问的上下文,您的代码有几个问题。
scanner
将任何内容添加到列表中。 那么,如何获得要计算的值呢?所以,这里是完整的代码:
import java.util.*;
public class arrayl {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
System.out.println("Enter the length of array :");
int n = sc.nextInt();
System.out.println("Enter List : ");
for (int i = 0; i < n; i++) {
list.add(sc.nextInt());
}
Iterator<Integer> itr = list.iterator();
int sum = 0;
int count = 0;
while (itr.hasNext()) {
int val = itr.next();
if (count % 2 == 0) {
sum += val;
}
count++;
}
System.out.println("Even Index Position Sum : " + sum);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.