0

この単純な問題を解決するのに 3 時間ほどかかりました。これが私が達成しようとしていることです: ユーザーに数字を入力するように依頼し、それらの数字を追加します。ユーザーが 5 つの数字を入力した場合、5 つの数字を追加する必要があります。

どんな助けでも大歓迎です。

  import java.util.Scanner;

  public class loopingnumbersusingwhile
  {
  public static void main(String args[])
  {
       Scanner kb = new Scanner(System.in);  

        int input;         
        System.out.println("How Many Numbers You Want To Enter");
        total = kb.nextInt();
        while(input <= kb.nextInt()) 
     {
         input++;

        System.out.println("How Many Numbers You Want To Enter" + input);
        int input = kb.nextInt();



       }                        




     }       

  }
4

5 に答える 5

2

input現在のコードは、あまりにも多くの目的で使用しようとしています: 現在入力されている数値、入力totalされた数値の量、および入力されたすべての数値の合計と入力される数値の量の両方として使用しようとしています。

これらの 4 つの個別の値を追跡するには、4 つの個別の変数が必要です。つまり、ユーザーが入力する数値の数、これまでに入力した数値、現在入力した数値、および合計です。

int total = 0; // The sum of all the numbers
System.out.println("How Many Numbers You Want To Enter");
int count = kb.nextInt(); // The amount of numbers that will be entered
for(int entered = 0; entered < count; total++)
{
    int input = kb.nextInt(); // the current number inputted
    total += input; // add that number to the sum
}
System.out.println("Total: " + total); // print out the sum
于 2013-11-12T17:10:38.863 に答える
0

あなたは二度何の数字を尋ねているようです.

public static void main(String args[])
{
 Scanner kb = new Scanner(System.in);  

 System.out.println("How Many Numbers You Want To Enter");
 int howMany = kb.nextInt();
 int total = 0;

 for (int i=1; i<=howMany; i++) {
   System.out.println("Enter a number:");
   total += kb.nextInt();
 }

 System.out.println("And the grand total is "+total);

}

于 2013-11-12T17:23:37.117 に答える
0

ユーザーが追加したい数字の数を取得した後に、次のコードを追加します。

int total;
for(int i = 0; i < input; i--)
{
    System.out.println("Type number: " + i);
    int input = kb.nextInt();
    total += input;
}

これを印刷するには、次のように言います。

System.out.println(total);
于 2013-11-12T17:05:32.597 に答える