Insane
Insane

Reputation: 305

JAVA do-while Loop doubles the output value

The following code outputs the sum, average, count of positive/negative numbers, count of all numbers correctly when ran first time. Because it loops, hence, the output remains on the console prompting user to enter numbers again. At this time, only sum shows the correct output, other values doubles. Please help me in fixing the loop. Thanks!

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

    }
}

Upvotes: 0

Views: 1513

Answers (2)

It would make sense that sum is the only one that outputs correctly; It's the only value you initialize every iteration of your outer loop.


the values count, positive, and negative aren't re-initialized each iteration, so when you begin the next iteration of your outer loop, they will start from wherever they printed as.

you might want to initialize them again every time you run the loop.

Upvotes: 3

Julien
Julien

Reputation: 2246

You never reinitialize your variables before entering in your do while loop for a second time.

So

else 
{
   int sum=0;
   do
   {

Should be

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

Upvotes: 0

Related Questions