2011-08-21 6 views
0
/* 
* 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를 더합니다. 누군가를 풀어 주면 고칠 수 있도록 도와줍니다.2를 입력 값에 포함해야합니다.

+0

(int number = 2; number ++)와 같은 것을 추가해야 하는가? –

+1

예 - 확실히 for 루프가 필요합니다. 그것은 숙제 문제처럼 보이기 때문에 목적에 대한 답변을주지 않음 :) – CoolBeans

+0

고마워요. 시도해 봤어. –

답변

2

루프가 필요합니다. 귀하의 의견은 올바른 방향을 암시하지만, 'for'루프를 올바르게 작성하는 방법을 보려면 Java 자습서를 참조하십시오. 초기 선언, 종료 조건 및 루프 단계의 세 부분이 있습니다. ++ 연산자는 변수에 하나만 추가한다는 것을 기억하십시오. + =를 사용하여 다른 값을 추가 할 수 있습니다. + =를 사용하여 루프 변수에 다른 값 (예 : 2)을 추가하면 짝수의 'if'테스트를 건너 뛸 수 있습니다. < = 및> = 비교 연산자 (프리미티브의 경우)를 사용하여 경계를 포괄적으로 테스트 할 수 있습니다. 그래서 당신은 다음과 같은 것을 원한다. (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 
+0

고마워. int sum = 0; for (int 현재 = 2; 현재 <= 번호; 현재 + = 2) { sum + = 현재; } System.out.println ("2와"+ 숫자 + "의 짝수 합은"+ sum "입니다. 이있어 printnumber } // 끝 : 정수를 입력보다 1 이상 : [DrJava 입력 상자] 2 포함 7 사이의 짝수의 합계는 다음과 같습니다 매력을 추천 작품 –

1
int sum = 0; 
for (int current = 2; current <= number; current += 2) 
    sum += current; 
관련 문제