2012-12-29 36 views
0

所以我試圖使 (EX)輸入一些值:1 -2 -3 2 5 正數的數量是5數負數是-3 總數是3平均數是。 6 我想這樣做,但是當我運行它時, 它不起作用 什麼部分是錯誤?容易循環不工作

import java.util.*; 


public class Welcome { 

public static void main(String [] args){ 

    Scanner input = new Scanner(System.in); 
System.out.print("Enter an int value, the program exits if the input is 0: "); 
    int num = input.nextInt(); 
    int countpos = 0; 
    int countneg = 0; 
    int totalnum = 0; 
    int total = 0; 
    double avg = 0.0; 

    while(num != 0){ 

     if(num < 0) 
      countpos++; 
     else 
      countneg++; 

     total = total + num; 
     totalnum++; 
    } 

    System.out.print("num of pos is: " + countpos); 
    System.out.print("num of neg is: " + countneg); 
    System.out.print("total is: " + total); 
    System.out.print("the avg is: " + total/totalnum); 

} 

}

+1

「不工作」 是不足夠的問題說明。哪部分產生不需要的輸出?預計什麼?什麼是實際?有沒有編譯器錯誤?例外?它會永遠運行嗎?吃冰激凌? – 2012-12-29 19:36:11

+1

不相關,但我認爲你想在你的''if''內切換循環中的標誌。當他們實際上是負面的時候,你似乎在計算正數。 – Fred

回答

2

你要做的num = input.nextInt();在環太

while(num != 0){ 

     if(num < 0) 
      countpos++; 
     else 
      countneg++; 

     total = total + num; 
     totalnum++; 

     num = input.nextInt(); 
    } 
+0

我做了,但它不工作tho –

+0

好吧,我簡化了一點。只需複製循環中的那一行 – gefei

+0

那麼while循環中的num是什麼因爲它在while循環中沒有聲明 –