簡體   English   中英

當兩個列表的大小不同時,將兩個列表中具有相同索引的元素的值相加

[英]Add the values of elements with the same index from two lists when the size of both the lists are different

如果 first.size() 大於 second.size() 那么結果列表應該是 first 的大小,否則它應該是 second 的大小。

import java.util.ArrayList;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

public class Source {
    public static List<Integer> getSumOfListElements(List<Integer> first,List<Integer> second){
     if(first.size()>=second.size()){
        List<Integer> third = new ArrayList<Integer>();
        for (int i = 0; i < first.size(); i++) {
        third.add(first.get(i) + second.get(i));
        }
        return third;
     }else{
      List<Integer> third = new ArrayList<Integer>();
        for (int i = 0; i < second.size(); i++) {
        third.add(first.get(i) + second.get(i));
        }
        return third;
     }
    }

    public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
       String str = in.nextLine();
       String str2 = in.nextLine();
       System.out.println(str);
       System.out.println(str2);
       List<Integer> list1 = Arrays.stream(str.split("\\s"))
        .mapToInt(Integer::parseInt)
        .boxed()
        .collect(Collectors.toList());
       List<Integer> list2 = Arrays.stream(str2.split("\\s"))
        .mapToInt(Integer::parseInt)
        .boxed()
        .collect(Collectors.toList());
       System.out.println(list1.size());
       System.out.println(list2.size());
       List<Integer> actual = Source.getSumOfListElements(list1,list2);
       System.out.println(actual);
    }
}

這是我寫的代碼。 它給出了不允許的異常操作。

您的代碼不起作用,因為當您嘗試從列表中添加兩個數字時(比如第一個列表大小 = 20,第二個列表大小 = 10),在某一時刻i變得比第二個列表大。 當您的 for 循環嘗試為該i查找元素時,您將收到錯誤消息。

要消除這種情況,您應該使用 try catch 塊來繞過添加並直接添加大列表的剩余元素。

看看下面的代碼:

public static List<Integer> getSumOfListElements(List<Integer> first, List<Integer> second) {

        // declare 'third' list with size of max('first' list, 'second' list)
        List<Integer> third = new ArrayList<>(Math.max(first.size(), second.size()));

        // loop through max('first' list, 'second' list) number elements in both lists
        for (int i = 0; i < Math.max(first.size(), second.size()); i++) {
            try {
                third.add(first.get(i) + second.get(i));

                // at one point either first or second will be finished.
                // (say second is finished at this point)
                // then add remaining elements of first to third
            } catch (IndexOutOfBoundsException e) {
                if (first.size() > second.size()) third.add(first.get(i));
                else third.add(second.get(i));
            }
        }
        return third;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM