Trying to add sum of all even integers between 2 and the input, and I just get the input back

StackOverflow https://stackoverflow.com/questions/23597143

  •  20-07-2023
  •  | 
  •  

Question

I'm attempting to write something for an assignment that takes the sum of all the even integers between 2 and the number entered by the user and prints it. If it is below 2 it should return an error. I'm getting an error for anything under 2, however, when I go have it return the sum it just returns the input.

I think I may have messed a variable up in this loop, but I can't see where I went wrong.

import java.util.Scanner;

public class EvenSum {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number larger than 2");
        int num = input.nextInt();
        if (num >= 2) {
            int sum = 0;
            for (int i = 2; i <= num; i +=2) {
                sum += i;
            }
            System.out.println("The sum of all even numbers between 2 and the input is " + num);
                } else {
            System.out.println("Invalid, please enter a number above 2");
        }
    }
}
Was it helpful?

Solution

System.out.println("The sum of all even numbers between 2 and the input is " + num);

should be

System.out.println("The sum of all even numbers between 2 and the input is " + sum);

There is a formula to compute the answer without a loop, by the way. But perhaps that is not the point of the exercise?

OTHER TIPS

It's because you return num instead of sum

Declare sum outside if statement, and print sum instead of num

package com.test;

import java.util.Scanner;

public class EvenSum {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number larger than 2");
        int num = input.nextInt();

        int sum = 0;
        if (num >= 2) {

            for (int i = 2; i <= num; i += 2) {
                sum += i;
            }
            System.out
                    .println("The sum of all even numbers between 2 and the input is "
                            + sum);
        } else {
            System.out.println("Invalid, please enter a number above 2");
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top