I just started using Java (SE 8)
So here's my code:
public class Foo {
public static int sum(int[] arr) {
int ans = 0;
for (int i = 0; i < arr.length; i++) {
ans += arr[i];
}
return ans;
}
public static int[] takeInput() {
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int arr[] = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = s.nextInt();
}
return arr;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int testCases = s.nextInt();
while (testCases-- > 0) {
int arr[] = takeInput();
System.out.println(sum(arr));
}
}
}
For some reason I get a NoSuchElementException
java.util.NoSuchElementException
at line 937, java.base/java.util.Scanner.throwFor
at line 1594, java.base/java.util.Scanner.next
at line 2258, java.base/java.util.Scanner.nextInt
at line 2212, java.base/java.util.Scanner.nextInt
at line 18, Solution.takeInput
at line 32, Solution.main
Basically have to find sum of elements of each arrays
Input:
2
5
1 2 3 4 5
3
10 20 30
Output:
15 60
What am I doing wrong here?