import java.util.Scanner;
import java.util.ArrayList;
public class Main{
public static double sum(ArrayList<Double> list){
double total = 0;
for(double value: list)
total += value;
return total;
}
private static ArrayList<Double> readNumbers(final Scanner in, final int count){
ArrayList<Double> list = new ArrayList<>();
double real;
while(count > list.size()){
System.out.print("Enter a number: ");
try{
real = new Double(in.nextLine());
list.add(real);
}catch(NumberFormatException e){
System.out.println("Error: Not a number!");
}catch(Exception e){
System.out.println("Error: Something went wrong!");
break;
}
}
return list;
}
public static void main(String[]args){
ArrayList<Double> list = readNumbers(new Scanner(System.in), 5);
double total = sum(list);
System.out.printf("Sum of %s is: %.2f%n", list, total);
}
}
Download
Comments
Post a Comment