2017-03-01 300 views
-3

我希望用戶在他們感覺喜歡時停止輸入數字。當我運行它時,它不會按照我想要的方式工作。感謝您提前提供的所有幫助。Java:while循環,輸入您的下一個數字或輸入「S」來停止

private static void whileLoop3() 
    { 
      System.out.printf("%n%nExecuting whileLoop3...%n%n"); 

      int count=0; 
      int total=0; 
      int average; 
      int temp; 

      //while loop 10 times 
      while(count < 10) 
      { 
       //input number from user 
       temp = input.nextInt(); 
       //add to total 
       total += temp; //same as total = total + temp 
       count++; //same as count = count + 10 
      } 

      System.out.printf("Count is %d%n", count); 
      average = total/count; 
      System.out.printf("The average of your numbers is %d%n", average); 


      System.out.printf("%nEnter your next number or \"S\" to stop: "); 

    } 
+4

「當我運行它,它不工作,我希望它的方式。」那麼,幾乎所有的SO問題都是如此。請更具體一些。 (提示:如果用戶可以輸入「S」而不是數字,那麼'nextInt'將會失敗...) –

+1

您是否嘗試過在循環內計算退出值? – efekctive

+3

你的問題是什麼?爲什麼不是循環內的最後一個打印語句?我沒有看到任何編碼努力來處理輸入的「S」。 – tnw

回答

0

import java.util.Scanner;

公共類的測試{

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    whileLoop3(); 
} 

static Scanner input = new Scanner(System.in); 

private static void whileLoop3() { 
    System.out.printf("%n%nExecuting whileLoop3...%n%n"); 

    System.out.printf("%nEnter your next number or \"S\" to stop: "); 

    System.out.println(); 

    int count = 0; 
    int total = 0; 
    int average = 0; 
    String strTemp = ""; 
    int temp; 

    // while loop 10 times 
    while (!strTemp.equals("S")) { 
     // input number from user 

     if (strTemp.equals("")) { 
     } else { 

      temp = Integer.parseInt(strTemp); 

      // add to total 
      total += temp; // same as total = total + temp 
      count++; // same as count = count + 10 
     } 
     strTemp = input.nextLine(); 
    } 

    System.out.printf("Count is %d%n", count); 
    if (count != 0) 
     average = total/count; 
    System.out.printf("The average of your numbers is %d%n", average); 

} 

}