2017-03-01 7 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

あなたの質問は何ですか?なぜあなたの最後のprint文がループ内にないのですか?私は、 "S"が入力されたことに対処するためのコーディング努力は見ません。 – tnw

答えて

0

import java.util.Scanner;

パブリッククラスTest {

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); 

} 

}

関連する問題