试图在2和输入之间添加所有偶数的总和,我只是得到输入

时间:2014-05-11 19:47:29

标签: java loops

我正在尝试为分配编写一些内容,该分配将2和用户输入的数字之间的所有偶数之和加起来并打印出来。如果它低于2,它应该返回一个错误。我收到2以下的任何错误,但是,当我去它时它返回它只返回输入的总和。

我想我可能在这个循环中弄乱了一个变量,但我看不出哪里出错了。

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");
        }
    }
}

3 个答案:

答案 0 :(得分:0)

这是因为您返回num而不是sum

答案 1 :(得分:0)

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

应该是

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

顺便说一下,有一个公式来计算没有循环的答案。但也许这不是演习的重点?

答案 2 :(得分:0)

在if语句之外声明sum,并打印sum而不是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");
        }
    }
}