I have the following piece of code that I've been looking at for a while now:
import java.util.Scanner;
public class SumExercise {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input start value");
int start = scanner.nextInt();
System.out.println("Input end value");
int end = scanner.nextInt();
int sum = computeSum(start,end);
System.out.println("Sum is of integers from "+start+" to "+
end+" is "+sum);
scanner.close();
}
public static void computeSum() {
for(int i = start; i <= end; i++) {
sum += i;
}
}
}
The way the program is supposed to work is that a user inputs a start value (int start = scanner.nextInt();
) and then afterwards an end value (int end = scanner.nextInt();
) and then the program will calculate the total sum (int sum = computeSum(start,end);
).
So if the user inputs 4 as the start value and 8 as the end value, the program will calculate "4+5+6+7+8" and then assign the value "30" to the variable sum
.
My exercise is to try and write the method computeSum
.
My attempt at solving this has been to try and write a loop that increases with 1 integer where it starts with the variable start
and ends with the variable end
:
public static void computeSum() {
for(int i = start; i <= end; i++) {
sum += i;
}
}
However it doesn't seem like I can get it to "link" with the computeSum(start,end)
. Is there something that I'm missing? My program is saying that the arguments are not applicable but I'm not sure what it means by that. I'm sorry, I'm quite new to programming.