0

I'm writing a java program to take a bunch of doubles the user inputs into the command line, add them together, and average them. The user can enter any amount of numbers. When they enter a negative number, the program does the adding/averaging. When i enter a number into cmd line it only lets me enter one. Can anyone help me improve this?

  import java.util.Scanner;
  public class Average
  {
     public static void main (String[] args)
     {
          Scanner keyboard = new Scanner(System.in);

          System.out.println("Statistics Program, assignment one, program 
          Two. Sean Kerr");
          System.out.println("\nPlease enter a series of numbers. To stop, 
          enter a negative number.");

          //initialize two doubles and an int for our variables: the total numbers,
          //the total added together, and the doubles the user enters into cmd line.

          int amount = 0;
          double totaladded = 0;
          double userinput = 0;

          userinput = keyboard.nextDouble();
          while (userinput >= 0);
          {
             if(userinput > 0 )
             {
                 totaladded = totaladded+userinput;
                 amount++;
             }
          }
          System.out.println("Numbers entered: " + amount);
          System.out.println("The average is: " + totaladded/amount);
      }
 }
3
  • 1
    You need to have userinput = keyboard.nextDouble(); inside the loop as well. Commented Jan 30, 2019 at 1:23
  • Thank you. I did that, and it lets me input a number but still only allows for one entry. Commented Jan 30, 2019 at 1:27
  • 2
    You have a bug while (userinput >= 0); - remove the ; Commented Jan 30, 2019 at 1:55

1 Answer 1

1

use a do while loop instead,

public static void main (String[] args) {
    Scanner keyboard = new Scanner(System.in);
    int amount = 0;
    double totaladded = 0;
    double userinput = 0;

    do {
        System.out.println("Statistics Program, assignment one, program Two. Sean Kerr");
        System.out.println("\nPlease enter a series of numbers. To stop, enter a negative number.");

        //initialize two doubles and an int for our variables: the total numbers,
        //the total added together, and the doubles the user enters into cmd line.

        userinput = keyboard.nextDouble();

        if(userinput > 0 ) {
            totaladded += userinput;
            amount++;
        }
    } while (userinput >= 0);

    System.out.println("Numbers entered: " + amount);
    System.out.println("The average is: " + totaladded/amount);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.