2014-09-05 75 views
-1

如何計算所有輸入的整數而不計0?如何計算輸入的整數不包括0?

也我想要的是,如果用戶輸入0然後輸出將是「沒有數字輸入除0」,但由於我有其他輸出它也將打印。

Scanner input = new Scanner(System.in); 
    System.out.print("Enter integers, input ends with 0: "); 
    int number = input.nextInt(); 

    if(number==0){ //This prints out along with the other system.out.println 
    System.out.println("No numbers were entered except 0"); 
    } 

    while(number!=0){ 
    count++; 
    total += number; 

    if(number > 0){ 
    positive++; 
    } 
    else{ 
    negative++; 
    } 
    number = input.nextInt(); 
    } 
    average = total*1.0/count; 

    System.out.println("The number of positives is " + positive); 
    System.out.println("The number of negatives is " + negative); 
    System.out.println("The total count is " + total); 
    System.out.printf("The average is " + average); 
     } 
     } 

    OUTPUT: 
    Enter integers, input ends with 0: 1 2 -1 3 0 
    The number of positives is 3 
    The number of negatives is 1 
    The total count is 4 //mine is reading out 5 entered integers instead of 4 
    The average is 1.25` 

    //0 is the only entered number 
    Enter integers, input ends with 0: 0 
    No numbers were entered except 0 
+0

有什麼理由不與您現有的代碼的工作? – 2014-09-05 03:28:45

+0

目前尚不清楚您面臨的問題,您是否可以更新您的問題並提供確切的問題詳細信息。 – Chaitanya 2014-09-05 03:59:14

+0

@Nathan 5/4是1.25, – 2014-09-05 03:59:41

回答

0

你似乎在期待着什麼不同的東西你問:

The total count is 4這是反映你正在進入,值的數量不限

使用值的總和System.out.println("The total count is " + count);會給你數值(數量)。

要當你輸入任何數字(0除外),刪除多餘的輸出,你的代碼更改:

System.out.println("The number of positives is " + positive); 
System.out.println("The number of negatives is " + negative); 
System.out.println("The total count is " + total); 
System.out.printf("The average is " + average); 

if (count > 0) 
{ 
    System.out.println("The number of positives is " + positive); 
    System.out.println("The number of negatives is " + negative); 
    System.out.println("The total count is " + total); 
    System.out.printf("The average is " + average); 
} 
+0

哦,你是對的!我還有一個問題,當我作爲一個整數輸入0時,它應該只打印沒有數字被輸入,除了0,但我也打印另一個輸出。 「輸入的正數爲」等等 – Nathan 2014-09-05 04:18:49

+0

檢查括號{}的位置。 「if> 0」部分不包含平均值計算或輸出。你可以檢查'if count> 0'或者其他東西,並把輸出放入那個條件部分 – chrisb2244 2014-09-05 04:20:42

+0

我試圖把輸出(其他的)放在while循環中,但它不起作用 – Nathan 2014-09-05 04:34:41