繁体   English   中英

Java 将输入值插入 ArrayList 并使用迭代器打印在 ArrayList 的偶数索引处存在的元素的总和

[英]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)向其中添加一些内容,其中elementint

根据您询问的上下文,您的代码有几个问题。

  1. 您尚未使用scanner将任何内容添加到列表中。 那么,如何获得要计算的值呢?
  2. 使用两个循环遍历列表并再次检查,这似乎不正确。
  3. 在循环内打印最终的 output 将打印多次。

所以,这里是完整的代码:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM