JAVA do-while Loop将输出值加倍

时间:2013-09-16 19:26:09

标签: java

以下代码在第一次运行时输出正数,负数,正数和所有数字的计数。因为它循环,因此输出保留在控制台上,提示用户再次输入数字。此时,只有sum显示正确的输出,其他值加倍。请帮我修理循环。谢谢!

public class Test {

    public static void main(String[] args) {
        long n; 
        int count=0;
        float average;
        int positive=0;
        int negative =0;


        Scanner in = new Scanner(System.in);

        do {

            System.out.print("Enter a positive or negative integers: ");
            n = in.nextLong();


            if (n == 0){
                System.out.println("Integers you've entered is invalid. Please re-launch the Program.");
            }
            else 
            {
                int sum=0;

                do
                {
                    //Find sum of the integers entered.
                    sum += n %10;
                    n /= 10;

                    //Count number of integers entered.
                    count++;

                    //Find average of the numbers
                    average = sum / count;

                    //Find a count of positive and negative numbers.
                    if(n < negative){
                        negative++;
                    }                                   
                    else{
                        positive++;
                    }

                } while (n != 0);

                n = sum;
                System.out.println("The Sum of the numbers: " + sum);
                System.out.println("The Average of the numbers: " + average);
                System.out.println("Positive numbers are: " + positive);
                System.out.println("Negative numbers are: " + negative);
                System.out.println("The count of all numbers: " +count);

            }

        } while(n != 0);

    }
}

2 个答案:

答案 0 :(得分:3)

有意义的是sum是唯一正确输出的人;它是您初始化外循环的每次迭代的唯一值。


每次迭代都不会重新初始化值countpositivenegative,因此当您开始外循环的下一次迭代时,它们将从无论他们在哪里打印。

每次运行循环时,您可能希望再次初始化它们。

答案 1 :(得分:0)

在第二次进入do while循环之前,您永远不会重新初始化变量。

所以

else 
{
   int sum=0;
   do
   {

应该是

else 
{
    int sum=0;
    count=0;
    average=0.0f;
    positive=0;
    negative =0;
    do
    {