BCJU19
BCJU19

Reputation: 13

Sum of all integers defined by user that are divisible by 5

What is not working is the sum part. Its not equaling the right number. Ex: user puts in 25 so the sum should be 75, but the program prints out 50.

My code:

import java.util.Scanner;
public class SumH4
{
    public static void main(String[] args)
    {
    //define data
    int x;
    int sum;

    //scanner is needed
    Scanner sc = new Scanner(System.in);

    //get user data and initialize variables
    System.out.println("Please input a positive whole number.");
    x = sc.nextInt();
    sc.nextLine();
    sc.close();
    System.out.println();
    sum = 0;

    //do computation
    for(int a = 0; a < x; a = a + 1)
     {
        if(a%5==0)
        {
            sum = sum + a;
        }

     }

    //print results
    System.out.println("Sum = " + sum);

    }
}

Upvotes: 1

Views: 1393

Answers (3)

Elliott Frisch
Elliott Frisch

Reputation: 201447

Your loop test should be <= (not <), also I suggest you define variables when you need them. Finally, you shouldn't close() a Scanner on System.in because that closes System.in and if you refactor your code you may cause yourself a lot of pain with that. So, I would change your method like

Scanner sc = new Scanner(System.in);
System.out.println("Please input a positive whole number.");
int x = sc.nextInt();
int sum = 0;
for (int a = 0; a <= x; a++) {
    if (a % 5 == 0) {
        sum += a;
    }
}
// print results
System.out.println("Sum = " + sum);

Upvotes: 3

splrs
splrs

Reputation: 2432

Change

for(int a = 0; a < x; a = a + 1)

to

for(int a = 0; a <= x; a = a + 1)

At the moment you're not including 25, that only goes upto 24 i.e. a < x means "while a is less than x", then you want "while a is less than OR EQUAL TO x".

Upvotes: 3

M A
M A

Reputation: 72854

You're not including the number itself that is input by the user. Simply change the for loop to the below so that the input x gets added:

for (int a = 0; a <= x; a = a + 1) {

Upvotes: 4

Related Questions