-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathArrayAggregate.java
More file actions
54 lines (44 loc) · 1.55 KB
/
Copy pathArrayAggregate.java
File metadata and controls
54 lines (44 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.*;
public class ArrayAggregate{
public static String sumOfArrays(String data){
String parts[] = data.split(":");
int arraySize;
try{
arraySize = Integer.parseInt(parts[0]);
}catch(NumberFormatException e){
throw new NumberFormatException("Provide a valid Integer");
}
if(arraySize < 0){
throw new NegativeArraySizeException("Provide a positive number");
}
int array[] = new int[arraySize];
int sum = 0;
if(parts.length-1 != arraySize){
throw new ArrayIndexOutOfBoundsException("Error: Index out of Bound");
}
try{
for(int i=0;i<arraySize;i++){
array[i] = Integer.parseInt(parts[i]);
sum += array[i];
}
}catch(NumberFormatException e){
throw new NumberFormatException("Provide a valid Value");
}
return "Sum of the array element is "+ sum;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the data");
String data = sc.nextLine();
try{
String result = sumOfArrays(data);
System.out.println(result);
}catch(NumberFormatException e){
System.out.println(e.getMessage());
}catch(NegativeArraySizeException e){
System.out.println(e.getMessage());
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}
}
}