1

This program is for adding elements of two lists. Console inputs are in this form:

"10, 20, 30"
"20, 30, 40, 50, 60"

output will be

[30, 50, 70 50, 60]

Note:- if one or both lists can be null or empty, output should be [] or empty list. In some testcases I get a Nullpointer exception error

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Source {
    public List<Integer> getSumOfListElements(List<Integer> first,List<Integer> second){
        List<Integer> list3 = new ArrayList<Integer>();
        if(second.isEmpty() || second==null){ //error Nullpointerexception is generated here
            if(first.isEmpty() || first==null){
                return list3;
            }else{
                return first;
            }
        }
        else if(first.isEmpty() || second==null){ //error Nullpointerexception is generated here
            return second;
        }

        int l1 = first.size();
        int l2 = second.size();

        if(l1>l2){
            for(int i=0; i<l1; i++){
                if(i<l2)
                    list3.add(first.get(i)+second.get(i));
                else
                    list3.add(first.get(i));
            }

        }//else part if l2>l1

        return list3;
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        String str1 = sc.nextLine();
        List<Integer> list1 = new ArrayList<Integer>();
        String st1 = str1.replaceAll("^\"|\"$", "");
        //same logic for list2 creation



        if(!st1.isEmpty()){
            String[] ss1=st1.split(", "); 
            for(int i=0;i<ss1.length;i++){
                list1.add(Integer.parseInt(ss1[i]));
            }
        }

        //same if function for list2

        if(st1.isEmpty()){
            System.out.println(list2);
        }....
        //same else if for list and for both
        ....   
        }else{
            Source obj = new Source();
            System.out.println("null object");
        }
    }
}

1
  • Hi. What is the error you are facing ? Commented Apr 1, 2020 at 8:33

1 Answer 1

1

The null check has to be first always like if(second.isEmpty() || second==null){ // This is wrong

if(second==null || second.isEmpty()){ // This will avoid nullpointer exception

The below line has an error

else if(first.isEmpty() || second==null){ //error Nullpointerexception is generated here

The correct code is

else if(first==null || first.isEmpty()){ //error Nullpointerexception is generated here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.