0

ユーザーに、最大 5 までの任意の数字をスペースで区切って入力するように求めようとしています。

例えば

数字を 5 つまで入力してください: 3 4 5

それらを整数の合計に追加し、後でそれらをカウンターで割ります

これらの数値の平均を取得します。

しかし、私のループは終わっていないようです。コードの何が問題になっていますか?

    int counter = 0 , sum = 0;

    Scanner scan = new Scanner(System.in);

    System.out.println("enter up to 5 numbers");

    while(scan.hasNextInt());{
    counter++;
    sum += scan.nextInt();
    }
    System.out.println(counter);
    System.out.println(sum);
4

6 に答える 6

0
  DataInputStream in = new DataInputStream(System.in);
  String[]label = {"quiz #","Total","Average"};
  int counter = 0;
  int theSum = 0;

   System.out.print("Enter up to 5 number : ");
   String[]tempNum = in.readLine().trim().split("\\s+");
   System.out.println();

 while (counter <= tempNum.length)
 {
    if ( counter == tempNum.length)
    {
     System.out.printf("%10s %12s\n",label[1],label[2]);
     counter = 0;
     break;
    } else {
     System.out.printf("%10s",label[0] + (counter+1) );
    }
    counter++;  
 }

 while(counter <= tempNum.length)
 {
    if ( counter == tempNum.length)
    {System.out.printf("%10d %10.2f\n",theSum,(double)(theSum/counter));
    } else 
    {System.out.printf("%10d",Integer.valueOf(tempNum[counter]));
     theSum += Integer.valueOf(tempNum[counter]);
    }
    counter++;
 }
于 2013-10-06T08:57:43.890 に答える
0
int counter = 0 , sum = 0;

Scanner scan = new Scanner(System.in);

System.out.println("enter up to 5 numbers");

while(scan.hasNextInt()){
    counter++;
    sum += scan.nextInt();
    if(counter >=5)
        break;
}
System.out.println(counter);
System.out.println(sum);
scan.close();

まず、「;」を削除する必要があります 前後while(scan.hasNextInt()){あります。;手段については、whileステートメントは完全です。第二に、コードを使用するときは、最終的に入力する必要がありCTRL + Zます。追加することで

if(counter >=5)
    break;

5つの数字を入力すると、入力が終了します。

于 2013-10-06T03:04:18.817 に答える