2012-07-31 126 views
-4

可能重复:
Taking average of user input number在java中停止循环

for (int n1 = in.nextInt(); n1 >= 0; n1 = in.nextInt()) 
    { 
      int total = 0; 
      int count = 0; 

      while (n1 >= 0) 
      { 
        n1 = in.nextInt(); 
        total = total + n1; 
        count = count + 1; 

      } 
      out.println(total); 
      out.println(count); 
    } 

我想要的一切,我输入要添加上的数字,这是正确的代码?它只增加了我的最后2个输入。我希望循环继续下去,直到用户输入负数,然后循环停止,然后输出我的总数和计数。

Scanner in = new Scanner(System.in); 
Printstream out = System.out; 
+0

你究竟想达到什么目的?为什么你不能在一个'while'循环中做到这一点? – 2012-07-31 03:25:34

+7

呵呵,所以以前的[伪代码来勾画这个](http://stackoverflow.com/a/11732204/851273)还不够好? – 2012-07-31 03:26:30

+0

它看起来像一个类似任务的问题,Jon Lin的上述链接应该这样做。请尝试通过上述链接中提到的伪代码实现 – hungr 2012-07-31 03:32:08

回答

2
int total = 0; 
int count = 0; 

while (true) { 
    int n = in.nextInt(); 
    if (n < 0) 
     break; 
    total += n; 
    count ++; 
} 
out.println(total); 
out.println(count); 
0

您的代码应该如下。

int total = 0; 
int count = 0; 
int n1; 

try 
{ 
    while((n1=Integer.parseInt(in.nextLine()))>=0) 
    { 
     total = total + n1; 
     count = count + 1; 
    } 
} 
catch(Exception e) 
{ 
    System.out.println(e.toString()); 
} 

out.println("Total  = "+total); 
out.println("Count  = "+count); 

Format df=new DecimalFormat("#.##"); 
out.println("Average = "+df.format((double)total/count));