Hello again. I am trying to create a simple code that can compute the average of a set of numbers read in using a scanner.

import java.util.Scanner;

public class Average
{
    public static void main(String[] args)
    {
        double number = 0;
        double total = 0;
        int count = 0;
        Scanner scan = new Scanner(System.in);
        while (number != -1)
        {
            System.out.println("Please enter a non negative number.");      
            number = scan.nextDouble();
            total = number++;
            System.out.println("The total is " + total);
            count++;
        }
        double average = total/count;
        System.out.println("The average is " + average);    

    }
}

The loop occurs but it won't end. I wanted the code to work like this: every time I enter a number that is not negative one ( I know it says non negative number, but i will fix this later, as I am not using negative numbers), the number entered would add to the total, the count would increase, and when -1 is entered, the compiler should exit out of the loop and compute the average and print it like so. But when I enter negative one, it prints -1 just like any other number. The total is always the same as the number just scanned in as well, so it is not increasing. Does anyone know what I did wrong?

total = number++;

Probably not what you intended!. This copies number to total, then adds 1 to number. You ned to add number to total.

To see what your code is doing, add a println just before the } at the end of the loop (after line 17) that prints out the value of number.

Does the value of total that is printed look correct when you enter several numbers?

It worked, but now I need the code to ignore adding the negative one to the total and the count total.

You can use an if test to prevent the relevant code being executed if input < 0 - just think about it.

Everytime you finish entering all values,you end with -1.So increase the total by 1 and decrease count by 1

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.