0

Ok, so far my program allows user input, recognizes how many numbers are stored in the array list and then outputs those numbers that are stored. How can I sum all the numbers entered by the user?

import java.util.Scanner;
import java.util.ArrayList;

public class lab5 
{
    public static void main (String[]args)
    {
        Scanner userInput = new Scanner(System.in);

        ArrayList<Integer> list = new ArrayList<>();

        //Creates initial value for nextInt variable
        int nextInt = -1; 

        //Create loop to store user input into array list until 0 is entered
        while((nextInt = userInput.nextInt()) != 0)
        {
            list.add(nextInt);
        }

        //Calculate average once zero is inputted
        if (nextInt == 0)
        {
            System.out.println("There are " + list.size() + " numbers in this array list");
            System.out.println("The numbers are " + list);
            System.out.println("The sum of the number are ")
        }
    }
}
1
  • Possibly duplicate, except that using an ArrayList at all in unnecessary. Commented Sep 24, 2013 at 16:58

1 Answer 1

0

You're close! All the numbers that are inputted to your program will reside in nextInt at some point. How can you use that fact to get the sum? Hint: you'll need to keep track of the sum outside of the while loop.

Sign up to request clarification or add additional context in comments.

8 Comments

Do I store the values outside to a new array? I'm so new at this :(
Not quite (you're already doing that with list). Picture this: your job is to wait by the door while people bring their dogs into a pet shop, and count how many dogs come in over the span of an hour. Each person could bring one or more dogs (you don't know in advance, you just count the dogs when they come in). So if you were in that situation, you would keep a SINGLE running tally in your head. How can you represent that single tally as a Java variable?
So would I want to change it to a for loop and add a counter in the parameters. I'm so confused.
Hang in there man; like I said, you're actually really close. The loop you have is fine as-is. It MUST be a while loop, because you want to be able to keep going indefinitely (until someone enters 0). A for loop isn't really appropriate for that. Not sure what you mean by the parameters, but right above the while loop, add int totalSum = 0;. Inside the loop, add to that sum every time you see a new value. Hint: that will look something like totalSum = totalSum + X;. I leave it to you to replace X with the correct variable.
I GOT IT! I was thinking way too hard about this. totalSum = totalSum + nextInt;
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.