2014-11-08 49 views
-3

我想找到一种方法来从用户输入的int倒数,然后添加每个第二个值,因为我计数降至0for循环递减2到0,并总结得到0之前生成的值

例如。

{用户输入10

程序递减计数8,6,4,2,0

然后加入10 + 8 + 6 + 4 + 2 + 0 = 30

}

我怎样才能做到这一点使用嵌套for循环

到目前为止我只能够采取用户输入,并每次倒数2。我达到0,但无法添加每秒的值。 我的代码:

到目前为止,它只是计数为0

公共类Week5b { 静态扫描仪userVal =新的扫描仪(System.in);

public static void main(String[] args) { 
    //printTable(); 
    reverseAddSkip(); 
public static void reverseAddSkip(){  

     System.out.println("Please enter an integer"); 


     for (int i = userVal.nextInt(); i >=0; i-=2){ 


     System.out.println(i) ; 
     }/* this creates a loop where the variable i is equal to user input; 
      the condition for the loop to continue is whether the input is larger or equal to 0; the update part of the loop takes 2 away each time, as if it were -- (which takes away one each time) */ 

} 

} 我怎么会写说出来数学? 将i- = 2的总和加到i的原始值上。 你键入11,它计数9 7 5 3 1,然后添加11 9 7 5 3 1,并给你总和。

不知道如何将每2个数字从用户值中减去2。

您输入把50,它倒计时以2比0 你把它51倒计时,以2比0 ,但我还没有找到离开总结得到0 之前生成的所有然后是数字:/

+1

你如何申报Java中的int变量?你如何在Java中添加两个数字? – 2014-11-08 15:47:31

回答

0

NoGlitching,

你需要看看你的程序的控制流 - 这是说,它需要在执行的路径。

你还应该看看使用更多变量

我会给你我会用伪代码,因为我觉得你是能够自己编写的代码是很重要的:

  • 建立一个叫做OriginalInput新的整数。
  • 创建一个名为RunningTotal的新整数。
  • 将RunningTotal设置为0.
  • 将用户的输入存储在OriginalInput中。
  • 循环通过OriginalInput。
    • 打印当前OriginalInput。
    • 将当前的OriginalInput添加到RunningTotal。
  • 当循环结束:
    • 打印RunningTotal。

我希望这会有所帮助。

+0

欣赏您的帮助bro,但我很难过,因为我必须使用嵌套for循环来做到这一点。基本上,我认为有一个数学解决方案。 i- = 2最终为0.所以即使i- = 2 + i 8- = 2 + 8 = 14?这将是加6,这是前2个数倒数2,但我不能表达它怎么做在纸上:( – NoGlitching 2014-11-08 16:00:39

0

编辑:

 // First you equalize j with i 

     input = userVal.nextInt(); 
     j = i; // Put the user input in j first. for instance 11. 

    for (int i = input; i >=0; i-=2) 
     { 
      if (i >= 0) // If i is not below 0 
       { 
       j += i; // Add to j what i has now (everytime -2) 
       // put a system out print here to show what was added 
       // J starts as 11 and adds 9,7,5,3,1 then nothing. So it ends as 36. 
       } 


      } 
    // outside the For loop after it ends but INSIDE your method, you get the sum from the variable j! 
+0

试过,但似乎只是从我输入的数字倒数到0,我想添加所有的数字,我必须计数,以达到0,所以如果有人输入12,程序应该输出42 – NoGlitching 2014-11-08 19:50:02

+0

这是我编辑的同一评论的解决方案,希望它有帮助,接受它,如果案件解决。否则,请留下一个答复 – 2014-11-08 23:50:46

+0

那么,它是有道理的,但不起作用。事情是,我只需要找到记住数字行的方法,或者将每个值存储在循环中倒数到一个变量中。知道该怎么做,所以想象一下,i = 2 ....所以每次2被带走,该值就被存储在一个变量中,显然,第一次它不会递减或递增,所以初始值价值也将被存储在同一个变量给出正确的结果,并仍然在勾选框我在打印答案之前,t倒数2到0 – NoGlitching 2014-11-10 16:55:48