Answer to Question #315851 in Java | JSP | JSF for Jay

Question #315851

Write a program that accepts a list of integers and computes their sum. The program should allow the user to enter any number of integers but an input of zero should terminate the list. For example if the user enters 2 5 6 12 8 2 0 the sum should be 35. If he/she enters 2 4 5 0 the sum should be 11 and if he enters 5 4 6 0 12 43 2 the sum should 15 i.e. only numbers before zero are summed. The rest are ignored and the program terminated. (5 marks)



1
Expert's answer
2022-03-22T10:16:25-0400
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;


public class Main {
        
    public static void main(String[] args) {
        System.out.println("Enter array separated by space"); 
        Scanner scanner = new Scanner(System.in);
        
        String s[]= scanner.nextLine().split(" ");


        List<Integer> values = new ArrayList<>();
        scanner.close();


        for(int i =0 ;i < s.length;i++){
            if(Integer.parseInt(s[i]) == 0)
            break;
            values.add(Integer.parseInt(s[i]));
        }    


        int sum = values.stream().mapToInt(Integer::intValue).sum();
        
        System.out.println(sum); 


    }
    
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS