I need to make two to the input value inclusive
/*
* 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
}
I need to calculate the sum of 2 to the input number inclusive however, it only takes the last number and add two to it. COuld someone help me fix this.
You need a loop. Your comment hints at the right direction, but you should look at the Java tutorials to see how to correctly write a 'for' loop. There are three parts: the initial declaration, the terminating condition and the loop step. Remember that the ++ operator only adds one to the variable. You can add other values using +=. If you use += to add a different value (like 2) to the loop variable, you can skip the 'if' test for even numbers. You can test for boundaries inclusively using the <= and >= comparison operators (for primitives). So you want something like this (in pseudocode, not 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
int sum = 0;
for (int current = 2; current <= number; current += 2)
sum += current;
精彩评论