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)
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);
}
}
Comments
Leave a comment