/*
* Application the reads an integer and prints sum of all even integers between two and input value
*/
import java.util.Scanner;
public class evenNumbers{
public static void main(String [] args){
int number;
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer greater than 1:");
number = scan.nextInt();
printNumber(number);
}// end main
/*declares an int variable called number and displays it on the screen*/
public static void printNumber(int number){
if (number < 2){
System.out.println("Input value must not be less than 2");
}
int sum = 2;
if(number % 2==0){
sum+= number;
}
System.out.println("Sum of even numbers between 2 and " + number + " inclusive is: " + sum);
}//end printnumber
}
我需要计算输入数字的总和2,但是,它只取最后一个数字并加2。有人帮我解决这个问题。
答案 0 :(得分:2)
你需要一个循环。您的评论暗示了正确的方向,但您应该查看Java教程,了解如何正确编写'for'循环。有三个部分:初始声明,终止条件和循环步骤。请记住,++运算符只向变量添加一个。您可以使用+ =添加其他值。如果使用+ =向循环变量添加不同的值(如2),则可以跳过偶数的“if”测试。您可以使用&lt; =和&gt; =比较运算符(对于基元)测试包含边界。所以你想要这样的东西(伪代码,而不是Java):
input the test value
Optional: reject invalid test value and **exit with message if it is not valid!**
initialize the sum variable to zero
for ( intialize loop variable to 2; test that loop var <= test value; add 2 to loop var )
{
add 'number' to the sum variable
}
display the sum
答案 1 :(得分:1)
int sum = 0;
for (int current = 2; current <= number; current += 2)
sum += current;