如何汇总用户输入的数字?

时间:2011-09-04 20:33:36

标签: java

我正在做一项任务,并且我认为大部分工作都会失效,我必须向用户提供随机数字,然后显示有多少负数以及正数然后总和和平均数,任何人都可以帮助我,因为我不能获取我的代码以显示正或负值的正确值或将其与总和相匹配。这是我到目前为止(我还添加了最后的休息,否则它进入了一个无限循环)

//Random number evaluation
package chapter_4;

import java.util.Scanner;


public class Four_One {

    public static void main(String[] args) {

       int positive = 0;
       int negative = 0;
       int sum = 0;
       int count = 0;

       Scanner input = new Scanner(System.in);

       System.out.print("Enter in a value, if 0 is entered program stops: ");
       int data = input.nextInt();


       while (data != 0) {
            sum += data;

            if (data < 0)
               negative++;

            else if (data > 0)
               positive++;

           count++;

        System.out.println("The number of positives is: " + positive);
        System.out.println("The number of negatives is:" + negative);
        System.out.println("The total is: " + sum);
        System.out.println("The average is: " + sum / data); 

        break; }

       }   

} 

4 个答案:

答案 0 :(得分:2)

  1. 您不是在nextInt()循环中要求while - 您确实想多次询问,对吗?
  2. 您的平均值不是平均值。我建议按计数而不是数据进行划分。

答案 1 :(得分:1)

在循环结束时(而不是中断)添加data = input.nextInt();

顺便说一下,你应该显示sum/(double)count(施法者加倍,所以你会看到分数)

答案 2 :(得分:1)

这可能会对你有所帮助。 说明:使用do-while循环可能更容易,因为它要求输入而不是检查输入。还将输入语句放在do-While循环中,以便它请求多个输入。

public static void main(String[] args)
{
   int positive = 0;
   int negative = 0;
   int sum = 0;
   int count = 0;
   Scanner input = new Scanner(System.in);
   int data = 0;
   do
   {
       System.out.print("Enter in a value, if 0 is entered program stops: ");
       data = input.nextInt();

       sum += data;
       count ++;

       if(data < 0)
           negative ++;
       else if(data > 0)
           positive ++;
    }
    //Stops if the value of data is ZERO(0) and continues if it's not
    while(data != 0);

    System.out.println("Positive Numbers = " + positive);
    System.out.println("Negative Numbers = " + negative);
    System.out.println("Sum of Numbers = " + sum);
    System.out.println("Total Numbers = " + count);
}

答案 3 :(得分:0)

import java.util.Scanner;

public class Four_One {

    public static void main(String[] args) {

        int positive = 0;
        int negative = 0;
        int sum = 0;
        int count = 0;

        Scanner input = new Scanner(System.in);

        System.out.print("Enter in a value, if 0 is entered program stops: ");

        int data = input.nextInt();

        while (data != 0) {
            sum += data;

            if (data < 0)
                negative++;

            else if (data > 0)
                positive++;

            count++;
            data = input.nextInt();
        }

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

}