2013-08-28 65 views
0

试图设计一个读取整数并打印2和输入值之间的所有偶数和的应用程序。任何人都可以帮助我最后一点?!Usind for while while循环更好

import java.util.Scanner; 

public class IntegerValue { 

    // main method 
    public static void main(String[] args) { 

     // Data fields 
     int a; 
     // end 

     Scanner sc = new Scanner(System.in); 

     System.out.println("Enter an integer greater than 1"); 
     a = sc.nextInt(); 
     if (a <= 1) { 
      System.out.println("Input Value must not be less than 2"); 
     } 
     while (a > 1) { 
      int sum = 0; 
      if (a % 2 == 0) { 
       sum += a; 
       a = a - 1; 
      } 
      System.out.println(sum); 
     } 

    } 
} 
+0

为什么不使用计算前n个偶数之和是'N *(N + 1)'更简单,更快的公式? –

回答

1

您需要定义您的sum变出while循环,否则会得到与循环的每次迭代重新初始化。如果你只是想要最后的总和,也应该在while循环之外打印总和。这里是代码更新,你可以尝试:

int sum = 0; 
while (a > 1) { 
      if (a % 2 == 0) { 
       sum += a; 
       a = a - 1; 
      } 
     } 
System.out.println(sum); 
2

已经指出了最重要的部分,已初始化的总和;但似乎他们错过了印刷部分;在循环执行后打印总和会更好。因此,这是怎么你的程序的最后一节最好的样子:

int sum = 0; 
while (a > 1) { 
    if (a % 2 == 0) { 
     sum += a; 
     a = a - 1; 
    } 
} 
System.out.println(sum);