WoeIs
WoeIs

Reputation: 1083

Program generates an error saying my method is not applicable for my arguments

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.

Upvotes: 0

Views: 66

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201429

You need to change your computeSum to accept start and end, and since you assign the result of computing the sum it should return an int (sum). Like,

public static int computeSum(int start, int end) {
    int sum = 0;
    for(int i = start; i <= end; i++) {
        sum += i;
    }
    return sum;
}

or, in Java 8+, use a lambda. Like,

public static int computeSum(int start, int end) {
    return IntStream.rangeClosed(start, end).sum();
}

or, apply Gauss's formula for summing natural numbers like

public static int computeSum(int start, int end) {
    return sumN(end) - sumN(start);
}

private static int sumN(int n) {
    return ((n + 2) * (n + 1)) / 2;
}

Upvotes: 2

Green
Green

Reputation: 2555

I think that the problem is with start, you cant assign it to i and same goes for sum and end. You need to make them global variables so both of the functions will recognize them

Upvotes: 0

Related Questions