2012-07-31 125 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));