Reputation: 5
The program asks that a method be created. The method takes two parameters: start and end, both integers. The method must sum all of the numbers between start and end that are divisible by 5. For example, if start is 1 and end is 30, the answer must be 105, since 5 + 10 + 15 + 20 + 25 + 30 = 105 are the numbers that are divisible by 5 and belong to the range of 1 and 5.
import java.util.*;
public class Divisor{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a start: ");
int start = input.nextInt();
System.out.print("Enter an end: ");
int end = input.nextInt();
int result6 = sumDivisor(start, end);
System.out.println(result6);
}
public static int sumDivisor (int start, int end){
int value = end;
for(int i = 5;i <= end;i = i + 5){
value = i;
System.out.print(i + " ");
}
return value;
}
}
Upvotes: 0
Views: 1984
Reputation: 835
You also have to take into account the situation where your start argument is not divisible by 5:
public static int sumDivisor (int start, int end){
int value = 0;
while (start % 5 != 0) {
start++;
}
for(int i = start;i <= end;i += 5){
value += i;
}
return value;
}
Upvotes: 1
Reputation: 61437
Instead of returning the last number, start it at 0
and add every number fulfilling your condition to it.
Upvotes: 0