简体   繁体   中英

How to take inputs to perform sum of list elements?

In this problem, I have to add elements from lists and print them using another list. I think I am doing it wrong because it gave me an empty list. I am new to java programming. Please help me out.

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

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

        List<Integer>result=new ArrayList<Integer>();
        int i;
        for(i=0;i<first.size();i++){
            result.add(first.get(i)+second.get(i));
        }
        return result;
    }

    public static void main(String[] args) {
        //CODE HERE
        Source s= new Source();
        List<Integer>a=new ArrayList();
        List<Integer>b=new ArrayList();
        Scanner sc=new Scanner(System.in);

        while (s.hasNextInt()) {
            int i = sc.nextInt();
            a.add(i);
        }

        while (sc.hasNextInt()) {
            int i = sc.nextInt();
            b.add(i);
        }

        List result1=s.getSumOfListElements(a,b);
        System.out.print(result1);
    }
}

input

10, 20, 30, 40, 50
12, 23, 34

The output should be like this:

[22, 43, 64, 40, 50]

You can do:

Scanner scanner = new Scanner(System.in);

String input1 = scanner.nextLine();
List<Integer> a = Arrays.stream(input1.split("[\\s,]+")).map(Integer::parseInt).collect(Collectors.toList());

String input2 = scanner.nextLine();
List<Integer> b = Arrays.stream(input2.split("[\\s,]+")).map(Integer::parseInt).collect(Collectors.toList());

List<Integer> result = new ArrayList<>();
for (int i = 0; i < a.size() && i < b.size(); i++) {
    result.add(a.get(i) + b.get(i));
}

for (int i = b.size(); i < a.size(); i++) {
    result.add(a.get(i));
}


System.out.print(result);

Output:

[22, 43, 64, 40, 50]

First, the main code doesn't read properly the values, as you provide non-int (comma) that can't be read by nextInt . I'd suggest you write the values separated by space/comma on one line, then split and parse to int

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String[] firstValues = sc.nextLine().split("[\\s,]+"); // input: 10 , 20, 40, 30
    String[] secondValues = sc.nextLine().split("[\\s,]+");

    List<Integer> a = Stream.of(firstValues).map(Integer::parseInt).collect(Collectors.toList());
    List<Integer> b = Stream.of(secondValues).map(Integer::parseInt).collect(Collectors.toList());

    List<Integer> result1 = getSumOfListElements(a, b);
    System.out.print(result1);
}

Then your sumOfList should handle the sizes of the lists, the first won't always be bigger (and your actual code lead to IndexOutOfBoundsException ), so:

  1. sum the items until you end the smallest list
  2. add all missing values of the biggest list
public static List<Integer> getSumOfListElements(List<Integer> first, List<Integer> second) {
    List<Integer> result = new ArrayList<>();
    int min_size = Math.min(first.size(), second.size());
    for (int i = 0; i < min_size; i++) {
        result.add(first.get(i) + second.get(i));
    }

    if (first.size() < second.size()) {
        result.addAll(second.subList(min_size, second.size()));
    } else {
        result.addAll(first.subList(min_size, first.size()));
    }

    return result;
}

Easiest multi-value input

Scanner sc = new Scanner(System.in);

List<Integer> a = new ArrayList<>();
for (String s : sc.nextLine().split("[\\s,]+"))
    a.add(Integer.parseInt(s));

List<Integer> b = new ArrayList<>();
for (String s : sc.nextLine().split("[\\s,]+"))
    b.add(Integer.parseInt(s));

List<Integer> result1 = getSumOfListElements(a, b);
System.out.print(result1);

Try this:

while (sc.hasNextInt()) {
  int i = sc.nextInt();
  a.add(i);
}
sc.next(); // add this
while (sc.hasNextInt()) {
  int i = sc.nextInt();
  b.add(i);
}
sc.close();

And in the helper method, you need to prevent out of bounds edge case:

public List<Integer> getSumOfListElements(List<Integer> first, List<Integer> second){
  List<Integer> result = new ArrayList<>();
  int firstSize = first.size(), secondSize = second.size();
  for(int i = 0; i < firstSize || i < secondSize; i++){
    int firstVal = i < firstSize ? first.get(i) : 0,
      secondVal = i < secondSize ? second.get(i) : 0;
    result.add(firstVal + secondVal);
  }
  return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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