TECH WITH KEVAL :
I am working this on Hacker Rank i am getting the error. Question is :- Finding the sum of elements of array.
Solution.java:28: error: missing return statement } ^ 1 error
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
/*
* Complete the simpleArraySum function below.
*/
static int simpleArraySum(int[] ar) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
int sum =0;
for(int i=0;i<=n;i++){
sum+=sc.nextInt();
}
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int arCount = Integer.parseInt(scanner.nextLine().trim());
int[] ar = new int[arCount];
String[] arItems = scanner.nextLine().split(" ");
for (int arItr = 0; arItr < arCount; arItr++) {
int arItem = Integer.parseInt(arItems[arItr].trim());
ar[arItr] = arItem;
}
int result = simpleArraySum(ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
}
}
I am still a beginner.Sorry if this is a silly question but this is my first time on hacker rank.I tried searching online but i didn't got an solution so i asked it here.
Yogen Rai :
Stacktrace is saying you are missing return statement. Return the sum value. Further, this method also needs refactoring to add nums in input array. I did like this:
static int simpleArraySum(int[] ar) {
int sum = 0;
for (int i = 0; i < ar.length; i++) {
sum += ar[i];
}
return sum;
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=345814&siteId=1