2013-02-08 46 views
0

我正在嘗試讀取未指定數量的整數,找到總和,積極,消極和平均的程序。我的問題是,要麼它只會運行,並允許鍵入一個整數,然後什麼都不做,或者用下面的代碼,它永遠不會讓你輸入數字,因此我無法越過。我有號碼= 0輸出正確。用戶輸入只出現一次或永遠不會停止在循環中

public class Compute { 

// Count positive and negative numbers and compute the average of numbers 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 

     int sum = 0; 
     positive = 0; 
     negative = 0; 
     total = 0; 

     System.out.println("Enter an integer, the input ends if it is 0: "); 
     int numbers = input.nextInt(); 

     do { 
      if (numbers > 0) { 
       positive++;//add 1 to positive count 
      } else if (numbers < 0) { 
       negative++;//add 1 to negative count 
      }//end else if 

      sum += numbers; //add integer input to sum 

      numbers = input.nextInt(); 
      total++; 
     } while (numbers != 0); 

     if (numbers == 0) { 
      System.out.println("No numbers are entered except " + numbers); 
     }//end if 
    } 
} 
+0

請工作更好地對您的代碼進行格式化。如果人們可以輕鬆閱讀你的代碼,你會得到更好的答案。 –

+0

輸入0退出循環。 –

+0

另外,請考慮在每次調用input.nextInt()之前向用戶輸入提示。否則,您如何知道是時候輸入新的輸入了?例如:'System.out.print(「請輸入下一個數字:」);'後面跟'numbers = input.nextIne();' –

回答

1

請嘗試以下代碼。終止循環並在任何執行時間將輸出類型0視爲輸入。

import java.util.Scanner; 

public class Compute { 

    // Count positive and negative numbers and compute the average of numbers 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 

     int sum = 0; 
     int positive = 0; 
     int negative = 0; 
     int total = 0; 

     System.out.println("Enter an integer, the input ends if it is 0: "); 
     int numbers = input.nextInt(); 

     do { 

      if (numbers > 0) { 
       positive++;// add 1 to positive count 
       sum += numbers; // add integer input to sum 
      } 

      else if (numbers < 0) { 
       negative++;// add 1 to negative count 
       sum -= numbers; // add integer input to sum 
      } 

      numbers = input.nextInt(); 
      total++; 

     } while (numbers != 0); 

     System.out.println("The number of positives is \t " + positive); 
     System.out.println("The number of negatives is \t " + negative); 
     System.out.println("The total count of number is \t " + total); 
     System.out.println("The sum of all number is \t" + sum); 
     System.out.println("The average is   \t" 
       + ((double) sum/(positive + negative))); 

    }// end main 
}// end Compute 
1

下面的代碼片段應該給你如何從控制檯讀取整數一個很好的例子:

Scanner scanner = new Scanner(System.in); 
do { 
    int i = scanner.nextInt(); 
    // ... 
} while (scanner.hasNext()); 

scanner.hasNext()方法調用將阻塞,直到用戶輸入在控制檯下一個號碼